如何使用swift

时间:2016-12-17 13:32:50

标签: swift swift3

我有这个变量

var = "[\"test\", \"test\", \"test\", \"test\", \"test\", \"test\", \"test\", \"test\"]"

如何将其转换为数组

[\"test\", \"test\", \"test\", \"test\", \"test\", \"test\", \"test\", \"test\"]

2 个答案:

答案 0 :(得分:3)

您的字符串包含数组的JSON表示 字符串元素。您可以将其转换为Swift [String]数组 使用JSONSerialization类:

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

答案 1 :(得分:-2)

在这里,试试这个:

var input = "[\"test\", \"test\", \"test\", \"test\", \"test\", \"test\", \"test\", \"test\"]"
let components = input.trimmingCharacters(in: ["\"", "[", "\"", "]"]).components(separatedBy: "\", \"")
相关问题