2016-11-12 26 views
1

這個代碼下面的代碼片斷:我在哪裏轉換此代碼出錯了,所以它不會把變量放在數組中?

if let dict = json?["Stats"] as? [String:AnyObject] { 

     if let newdict = dict["biggestWin"] as? [[String : AnyObject]] { 
     self.bigWinPlayer1Goals = newdict.flatMap { $0["player1_goals"] as! String!} 
     print (self.bigWinPlayer1Goals) 
} 

輸出:

[ 「1」]

然而,1被包含在陣列中 - 這我不想要的。所以我已將代碼重新寫入:

if let newdict = dict["biggestWin"] as? [String : AnyObject] { 
     let bigWinPlayer1Goals = newdict ["player1_goals"] as? String 
     print (bigWinPlayer1Goals!) 
} 

但是,這不起作用,並且不輸出任何內容。

我哪裏錯了?

這是有問題的數組:

["Stats": { 
biggestWin =  (
      { 
     "player1_goals" = 1; 
     "player2_goals" = 2; 
    } 
); 
goalDifference = "-17"; 
goalsConceded = 32; 
goalsScored = 15; 
totalDraws = 3; 
totalLosses = 10; 
totalWins = 1; 
winPercentage = "7.14%"; 
}] 

我希望能夠存儲player1_goalsplayer2_goals在兩個獨立的變量。

+0

請將使用過的數據和您的預期輸出看起來像 – shallowThought

回答

2

dict["biggestWin"]返回的值是類型[字符串:AnyObject]],即ArrayAnyObject s。

if let data = dict["biggestWin"] as? [[String : AnyObject]] { 
    let newdict = data.first! 
    let bigWinPlayer1Goals = newdict ["player1_goals"] as? String 
    print (bigWinPlayer1Goals!) 
} 
+0

好極了!謝謝。所以我錯過了.first命令。這到底是什麼呢? (除了解決我的代碼!)只需返回數組中的第一個? – Northfield82

+0

返回包含數組的第一個元素的「Optinal」(如果存在),或者不存在其他元素。 https://developer.apple.com/reference/swift/array – shallowThought

相關問題