Swift-将数组转换为结构

Swift-将数组转换为结构,swift,Swift,我有一个包含如下数据列表的数组data=[City,ZipCode,gpsLat,gpsLong] 我试图在struct中进行如下转换 struct Location { var zipCode: Double var nameCity: String var gpsLat: DOuble var gpsLong: Double } 我正在使用for in循环 var resultat :[Location] = [] for item in Data {

我有一个包含如下数据列表的数组
data=[City,ZipCode,gpsLat,gpsLong]

我试图在struct中进行如下转换

struct Location  {
    var zipCode: Double
    var nameCity: String
    var gpsLat: DOuble
    var gpsLong: Double
}
我正在使用
for in
循环

var resultat :[Location] =  [] 
for item in Data {
    resultat.append(Location(zipCode: Data[item][0], City : Data[item][1],  gpsLat : Data[item][2], gpsLong : Data[item][3]))
}
我明白了

Cannot convert value of type '[String]' to expected argument type 'Int'

正如@Achu所说,您应该使用
item[0]
,而不是'Data[item][0]

一个
用于。。。在
中,循环定义一个新的局部变量,该变量包含数组中的每个元素

因此,如果您有一个数组:

let array = ["now", "is", "the", "time"]
通常,您会像这样在阵列中循环:

for item in array {
    print(item)
}
for index in array.indices {
    let item = array[index]
    print(item)
}
这是推荐的方法

如果要循环索引,则代码如下所示:

for item in array {
    print(item)
}
for index in array.indices {
    let item = array[index]
    print(item)
}
或者这个:

for index in 0..<array.count {
    let item = array[index]
    print(item)
}
这将有助于提高产量

item at index 0 = 'now'
item at index 1 = 'is'
item at index 2 = 'the'
item at index 3 = 'time'
您还可以将该循环作为forEach编写:

array.enumerated().forEach() { (index, item) in
    print("item at index \(index) = '\(item)'")
}
综上所述,您的用例实际上并不适合循环。如果数组仅包含一组
位置
属性,则可能需要:

if let zipCode = Data[0] as Double,
   let nameCity = Data[1] as? String,
   let gpsLat = Data[2] as? Double,
   let gpsLong = Data[3] as? Double {

    let location = Location(zipCode: zipCode,
        nameCity: nameCity,
        gpsLat: gpsLat,
        gpsLong: gpsLong)
    // Do something with the location we just created
}

(顺便说一句,
Double
是存储zipcodes的一种不好的方法。我建议使用int或string。int工作得很好,除非您的邮政编码前导零,在这种情况下,前导零将被截断。)

将数据[item]更改为item。for loop为您提供了数据数组中的项注意:在Swift中,类型和类应大写,但方法名和变量名不应大写。因此,如果你有一个“stuff”数组,它应该被命名为
data
,而不是
data