将包含整数数组的字符串转换为整数数组IN Swift

时间:2017-03-02 07:31:10

标签: arrays swift

我有一个

let locationjson: String = "[\"43786\",\"55665\",\"62789\",\"90265\"]"

我想将其转换为Swift中的Arraylist / List ...我已经在StackOverflow上搜索过但无法找到适合Swift的解决方案。

我希望输出为List<Integer>,其中包含值[43786,55665,62789,90265]

3 个答案:

答案 0 :(得分:4)

正如马丁在评论中提到的JSONSerialization是你的朋友:

let locationjson = "[\"43786\",\"55665\",\"62789\",\"90265\"]"
let data = locationjson.data(using: .utf8)!
if let array = (try? JSONSerialization.jsonObject(with: data)) as? [String] {
    let intArray = array.flatMap { Int($0) }
    print(intArray)
}

答案 1 :(得分:2)

您可以使用flatMap执行此操作:

let locationjson  = ["43786", "55665", "62789", "90265"]
let result = locationjson.flatMap { Int($0) }

答案 2 :(得分:-1)

你的意思是这样的吗?

var str:String = "[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"]"
str = str.replacingOccurrences(of: "[", with: "")
str = str.replacingOccurrences(of: "]", with: "")
str = str.replacingOccurrences(of: "\"", with: "")

var arrStrNums = str.components(separatedBy: ",")

var nums:[Int] = []

for strNum in arrStrNums {
    if let num = Int(strNum) {
        nums.append(num)
    }
}

print("Number list: \(nums)")

输出:

Number list: [1, 2, 3, 4, 5, 6]