2016-11-16 94 views
1

在Swift 2.3中,我可以將[String:AnyObject]作爲! [[Double]]。但是,在Swift 3.0中使用相同的對象時,我無法將其轉換爲[[Double]]。當我投它,而不是作爲一個[[AnyObject]][[Any]],循環並嘗試轉換,我收到以下錯誤:如何在Swift 3.0中將我的數組數組作爲[[Double]]?

Could not cast value of type '__NSArrayI' (0x10783ec08) to 'NSNumber' (0x106e47320).

下面的代碼工作在我的雨燕2.3的實現,但不是雨燕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循環中顯式聲明類型或轉換後得到此工作。任何幫助是極大的讚賞。

回答

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) 
    } 
} 
+0

謝謝。這非常有幫助!必須將陣列的協調員視爲? [[AnyObject]],然後創建ArrayOfCoordinate = theArraysOfCoordinates [0] as! [[Double]] – stvnmcdonald

+0

這意味着'geometryDic [「coordinates」]'包含具有2個嵌套數組的數組,並且您沒有顯示您的響應,請檢查編輯後的答案,使用數組的第一個屬性而不是索引爲0的下標'如果數組爲空,這會導致你崩潰。 –

相關問題