2016-12-17 37 views

回答

3

您的字符串包含字符串元素的數組的JSON表示形式。

let jsonString = "[\"foo\", \"bar\", \"baz\"]" 
print("JSON:", jsonString) 

let jsonData = jsonString.data(using: .utf8)! // Conversion to UTF-8 cannot fail. 

if let array = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [String] { 
    // `array` has type `[String]`. 

    // Let's dump the array for demonstration purposes: 
    print("\nArray:") 
    for (idx, elem) in array.enumerated() { 
     print(idx, elem) 
    } 
} else { 
    print("malformed input") 
} 

輸出:

 
JSON: ["foo", "bar", "baz"] 

Array: 
0 foo 
1 bar 
2 baz 
您可以使用 JSONSerialization類將其轉換爲雨燕 [String]陣列
-2

這裏,試試這個:

var input = "[\"test\", \"test\", \"test\", \"test\", \"test\", \"test\", \"test\", \"test\"]" 
let components = input.trimmingCharacters(in: ["\"", "[", "\"", "]"]).components(separatedBy: "\", \"") 
相關問題