Swift在For循环中附加数组

时间:2014-09-10 07:41:54

标签: ios arrays swift append

让我从代码开始:

    var lat1:CLLocationDegrees = 50.102760 

    var lat2:CLLocationDegrees = -26.135170

    .
    .
    .

    var lat191:CLLocationDegrees = 60.289139

    var LocCount = 191

    for var iLat = 3; iLat == LocCount; ++iLat{
            AirportLat.append("lat" + iLat)    
     }

我尝试的是去计算应该附加到我的数组的var的名称有没有办法做到这一点?

2 个答案:

答案 0 :(得分:2)

嗯,这是一个很难做到的事情。

怎么样:

var latArray = <CLLocationDegrees>() 
latArray += [50.102760] 
latArray += [-26.135170]
.
.
.
latArray += [60.289139]

println("LocCount check = \(latArray.count)")

更好的方法是将纬度放入文件中(这样你就可以更改它们,添加它们等,而无需重新编译代码)并阅读它们,但我会留下作为一项练习...

...如果您想使用其他答案的字典构思,可以添加

for i in 0 ..< latArray.count {
    dict["lat\(i+1)"] = latArray[i]
}

答案 1 :(得分:2)

首先定义191个变量并不是一个好习惯。使用Dictionary代替密钥为:lat1lat2 .... lat191

之后,您可以循环Dictionary值并使用它们进行操作。

但是如果您仍想将所有变量聚合到Array,可以使用class_copyIvarList来获取所有以lat开头的变量并写为:

class Myclass : NSObject{

    var lat1:CLLocationDegrees = 50.102760
    var lat2:CLLocationDegrees = -26.135170
    var lat3:CLLocationDegrees = 60.289139

    var AirportLat:Array<CLLocationDegrees> = []

    func fetchValues() -> Array<CLLocationDegrees>{
        var aClass : AnyClass? = self.dynamicType
        var propertiesCount : CUnsignedInt = 0
        let propertiesInAClass : UnsafeMutablePointer<Ivar> = class_copyIvarList(aClass, &propertiesCount)

        for var i = 0; i < Int(propertiesCount); i++ {
            var propName:String = NSString(CString: ivar_getName(propertiesInAClass[Int(i)]), encoding: NSUTF8StringEncoding)

            var propValue : AnyObject! = self.valueForKey(propName)

            if propName.hasPrefix("lat") {
               AirportLat.append(propValue as CLLocationDegrees)
            }

        }//for

        return AirportLat
    }       
}

var cc = Myclass()
cc.fetchValues()

输出:

[50.10276, -26.13517, 60.289139]

评论:该类必须继承NSObject