gpt4 book ai didi

swift - 如何使用swift将字符串变量转换为数组

转载 作者:行者123 更新时间:2023-11-28 16:00:09 25 4
gpt4 key购买 nike

我有这个变量

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

如何将其转换为数组

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

最佳答案

您的字符串包含 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 foo1 bar2 baz

关于swift - 如何使用swift将字符串变量转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41199115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com