【问题标题】:Swift append Array in For LoopSwift 在 For 循环中追加数组
【发布时间】:2014-11-03 18:36:05
【问题描述】:

让我从代码开始:

    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 的名称有没有办法做到这一点?

【问题讨论】:

  • 你可能想要一个CLLocationCoordinate2D(纬度和经度)结构的数组,而不仅仅是CLLocationDegrees。更好的是创建一个Airport 类,其中CLLocationCoordinate2D 作为属性之一(以及机场名称、机场代码等)。

标签: ios arrays swift append


【解决方案1】:

嗯,这很难做到。

怎么样:

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]
}

【讨论】:

    【解决方案2】:

    首先,定义 191 个变量并不是一个好习惯。使用 Dictionary 代替键是:lat1, lat2 .... 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 2016-08-22
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 2018-10-04
      相关资源
      最近更新 更多