在Array中寻找一个值并返回第二个值

时间:2017-10-18 11:38:59

标签: swift xcode

我有一个像:

这样的数组
[
    ["Reichertshofen", "ssh -p 10001 speed@norhfa.anywareip.net -L 13389:192.168.23.14:3389 -f sleep 50"],
    ["Zentralbuero", "ssh -p 10001 speed@nozbfa.anywareip.net -L 13389:192.168.38.14:3389 -f sleep 50"]
]

我想寻找像“Reichertshofen”这样的第一个值,并获得第二个字符串。

我该怎么做?

4 个答案:

答案 0 :(得分:0)

  

我想寻找像“Reichertshofen”这样的第一个值,并获得第二个字符串。

你拥有的是一组数组。如果添加一些换行符会更清楚:

[
  ["Reichertshofen", "ssh -p 10001 speed@norhfa.anywareip.net -L 13389:192.168.23.14:3389 -f sleep 50"],
  ["Zentralbuero", "ssh -p 10001 speed@nozbfa.anywareip.net -L 13389:192.168.38.14:3389 -f sleep 50"]
]

所以你要求的是第一个子阵列的第二个元素。换句话说,如果你有:

let people : [[String]] = [["Reichertshofen", "ssh -p 10001 speed@norhfa.anywareip.net -L 13389:192.168.23.14:3389 -f sleep 50"], ["Zentralbuero", "ssh -p 10001 speed@nozbfa.anywareip.net -L 13389:192.168.38.14:3389 -f sleep 50"]]

然后你想要的元素是:

let element = people[0][1]

请记住,数组从零开始索引,因此数组中的第一个元素位于索引0处。

答案 1 :(得分:0)

假设所有数组都包含(至少)2个项目,并且您希望始终搜索第一个项目

let data = [
    ["Reichertshofen", "ssh -p 10001 speed@norhfa.anywareip.net -L 13389:192.168.23.14:3389 -f sleep 50"],
    ["Zentralbuero", "ssh -p 10001 speed@nozbfa.anywareip.net -L 13389:192.168.38.14:3389 -f sleep 50"]
]

let search = "Reichertshofen"
if let found = data.first(where: {$0[0] == search }) {
    let script = found[1]
    print(script)
}

但是我强烈建议使用简单的自定义结构而不是嵌套数组。名称比索引更具描述性。

struct Connection {
    let name, script : String
}

let data = [
    Connection(name: "Reichertshofen", script: "ssh -p 10001 speed@norhfa.anywareip.net -L 13389:192.168.23.14:3389 -f sleep 50"),
    Connection(name: "Zentralbuero", script: "ssh -p 10001 speed@nozbfa.anywareip.net -L 13389:192.168.38.14:3389 -f sleep 50")
]

let search = "Reichertshofen"
if let found = data.first(where: {$0.name == search }) {
    let script = found.script
    print(script)
}

答案 2 :(得分:0)

这本质上是一本字典,所以我倾向于将数据表示为一个。

let array = [
    ["Reichertshofen", "ssh -p 10001 speed@norhfa.anywareip.net -L 13389:192.168.23.14:3389 -f sleep 50"],
    ["Zentralbuero", "ssh -p 10001 speed@nozbfa.anywareip.net -L 13389:192.168.38.14:3389 -f sleep 50"]
]

Swift 4

let sequence = array.flatMap
{   entry -> (String, String)? in
    guard entry.count == 2 else { return nil }
    return (entry[0], entry[1])
}
let dictionary = Dictionary(uniqueKeysWithValues: sequence)

Swift 3

let dictionary = array.reduce([String:String]())
{   (dict, entry) in
    guard entry.count == 2 else { return dict }
    var dict = dict
    dict[entry[0]] = entry[1]
    return dict
}

在那里形成它只是:

if let result = dictionary["Reichertshofen"]
{
    print(result)
}

答案 3 :(得分:-1)

// 1
for array in arrays {
    // 2
    if let index = array.index(of: "abc"),
        // 3
        (index + 1) < array.count {

        // 4
        return array[index + 1]
    }
}
  1. 枚举数组数组
  2. 查找所需元素的索引
  3. 检查该索引之后是否有下一个元素
  4. 返回所需的值