如何从两个数组创建一个结构?

时间:2016-07-25 06:33:34

标签: swift data-structures

我有SearchViewController我创建了“Data”类来加载SearchViewController。

//File.swift
    class Data {

        var add1: String
        var add2: String

        init(add1: String, add2: String) {
            self.add1 = add2
            self.add1 = add2
        }
    }


//ViewController.swift
//This is the part that I want to load from two arrays of strings.
var entries = [Data]()

entries = [
Data(add1: "Canada", add2: "Ottawa"),
Data(add1: "USA", add2: "Washington"),
Data(add1: "Japan", add2: "Tokyo"),
Data(add1: "Denmark", add2: "Copenhagen")
]

我的搜索控制器数据列表继续进行。我将有大约1000个值。因此,我想从两个数组加载此类,如下所示。

let arr1: [String] = ["Canada", "USA", "Japan", "Denmark"]
let arr2: [String] = ["Ottawa", "Washington", "Tokyo", "Copenhagen"]

2 个答案:

答案 0 :(得分:2)

尝试迭代循环中的值并附加到entries数组

for i in 0..<arr1.count {
    // create struct from array data
    let data = Data(add1: arr1[i], add2: arr2[i])

    // insert to your array
    entries.append(data)           
}

答案 1 :(得分:2)

您可以在此处使用函数zip将两个数组合并为一个元组(String, String),然后map的数组,该数组按顺序排列为Data数组

let arr1 = ["Canada", "USA", "Japan", "Denmark"]
let arr2 = ["Ottawa", "Washington", "Tokyo", "Copenhagen"]
let data = zip(arr1, arr2).map { Data(add1: $0.0, add2: $0.1) }
for d in data { print("\(d.add1) - \(d.add2)") }

打印:

Canada - Ottawa
USA - Washington
Japan - Tokyo
Denmark - Copenhagen

我还建议您将类型Data更改为struct而不是class,如果您没有充分理由将其class更改为var re = /(?:^|[ ])£([a-zA-Z]+)/gm; var str = 'This product price is £15.00 and old price is £19.00'; var identifiedWords; while ((identifiedWords = re.exec(str)) != null) { if (identifiedWords.index === re.lastIndex) { re.lastIndex++; } // View your result using the "identifiedWords" variable. // eg identifiedWords[0] etc. } }