【问题标题】:How do I cast my array of arrays as a [[Double]] in Swift 3.0?如何在 Swift 3.0 中将我的数组转换为 [[Double]]?
【发布时间】:2016-11-16 05:19:37
【问题描述】:

在 Swift 2.3 中,我可以使用 [String:AnyObject] 并将其转换为! [[Double]]。但是,在 Swift 3.0 中使用相同的对象,我无法将其转换为 [[Double]]。当我将其转换为 [[AnyObject]][[Any]] 时,循环并尝试转换,我收到以下错误:

无法将“__NSArrayI”(0x10783ec08)类型的值转换为“NSNumber”(0x106e47320)。

以下代码适用于我的 Swift 2.3 实现,但不适用于 Swift 3.0

func extractCoordinatesForArea() {
    // This first line is where it crashes
    let theArraysOfCoordinates = myObject.geoArea!["geometry"]!["coordinates"] as! [[Double]]
    var newArea:[CLLocationCoordinate2D] = []
    for coordArray in theArraysOfCoordinates {
        // x is LONG, LAT
        let x = [coordArray[0], coordArray[1]]
        // Reverse the coordinates because they are stored as LONG, LAT on the server
        let y = CLLocationCoordinate2DMake(x[1],x[0])
        print(y)
        newArea.append(y)
    }
}

虽然错误是有道理的,但在明确声明类型或在 for 循环中进行转换后,我似乎无法让它工作。非常感谢任何帮助。

【问题讨论】:

    标签: arrays swift3


    【解决方案1】:

    试着像这样打破第一条语句。

    if let geometryDic = myObject.geoArea["geometry"] as? [String:Any], 
       let coordinatesArray = geometryDic["coordinates"] as? [Any] {
       let theArraysOfCoordinates = coordinatesArray.first as? [[Double]] {
        var newArea:[CLLocationCoordinate2D] = []
        for coordArray in theArraysOfCoordinates {
            //There is no need to create another array X you can directly use coordArray
            // Reverse the coordinates because they are stored as LONG, LAT on the server
            let coordinate = CLLocationCoordinate2DMake(coordArray[1],coordArray[0])
            print(coordinate)
            newArea.append(coordinate)
        }
    }
    

    【讨论】:

    • 谢谢。这有很大帮助!必须将 theArraysOfCoordinates 转换为? [[AnyObject]] 首先,然后创建 theArrayOfCoordinate = theArraysOfCoordinates[0] 为! [[双]]
    • 这意味着 geometryDic["coordinates"] 包含带有 2 个嵌套数组的数组并且您没有显示您的响应,请检查编辑后的答案,使用数组的第一个属性而不是索引为 0 的下标这将如果数组为空,会导致崩溃。
    猜你喜欢
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2013-11-05
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    相关资源
    最近更新 更多