我正在使用包含整数数组(“[1,4,5,6,7]”)的列对我的解析服务器进行查询,我想将此结果用作变量作为数组。我应该以什么方式投出这个来确保这种情况发生?
as! [Int]
不适合我。
答案 0 :(得分:2)
我想要做的第一件事是:
鉴于此字符串:
var str = "[1,2,3,4,5,6]"
str = str.replacingOccurrences(of: "[", with: "")
str = str.replacingOccurrences(of: "]", with: "")
str = str.replacingOccurrences(of: " ", with: "") //This if you have spaces between comas and numbers
let array = str.components(separatedBy: ",").flatMap({ Int($0)})
你将拥有一个整数数组
希望它会有所帮助
答案 1 :(得分:1)
这是一种JSON格式,你可以解析它:
import Foundation
var str = "[1,2,3]"
let data = str.data(using: .utf8)
let json = try? JSONSerialization.jsonObject(with: data!)
print(json)
// output:
// [1, 2, 3]