2017-06-16 68 views
-1

我想將JSON數組轉換爲一個String數組,然後將字符串數組附加到一個字符串數組。 JSON數組我處理如下:將JSON數組附加到字符串數組

let allPosts = JSON(value) 

//using SwiftyJSON to do something else 

// [["0","1","2","3"],["username1","username12","username123","username1234"]] 

我到目前爲止已經試過(我用SwiftyJSON):

let postsIndec = allPosts[0].arrayValue 

//also tried: self.indec.append(contentsOf: postsIndec) //Xcode tells me to remove "contentsOf: " 

self.indec.append(postsIndec) // indec being: var indec = [String]() 

在最後一行我得到這使得錯誤Cannot convert value of type '[JSON]' to expected argument type 'String'有意義但明顯將其轉換爲字符串

由於子陣列中的字符串數可能大於或小於4(此處用作示例),因此我無法循環預定義的次數。你能幫助我嗎?我找不到任何描述相同問題的問題。

+0

它是不是真的清楚你正在嘗試做什麼? swiftJSON返回的數據是'[[「0」,「1」,「2」,「3」],[「username1」,「username12」,「username123」,「username1234」]]。你想提取每個數組到一個單獨的數組,例如'array1 = [「0」,「1」,「2」,「3」]' – Lamar

+0

'allPosts'是一個包含數組的JSON數組,我想添加第一個「allPosts」數組與包含字符串的'self.indec'數組中已有的數組有關。 @Lamar – Moritz

+0

我刪除我的答案,因爲你的評論仍然不清楚,如果你說它是字符串已經然後做'postsIndec.map {indec.append($ 0)}' – Lamar

回答

1

嘗試使用地圖轉換[JSON]到[字符串]:

self.indec.append(contentsOf: postsIndec.map {$0.stringValue}) 
+0

這會導致類似的錯誤:/ ...:''map'產生'[T]',而不是預期的上下文結果類型'String'' – Moritz

+0

@Moritz更新了追加數組而不是單個元素的答案。 – srvv

+0

這就是我一直在尋找的!非常感謝! – Moritz