我是那种类型的String,例如:
var test:String = "[1, 0, 4]";
我需要将其转换为Int:
数组var testConverted:[Int] = [ 1, 0, 4 ];
答案 0 :(得分:2)
您需要使用stringByTrimmingCharactersInSet
修剪开始和结束括号,然后使用componentsSeparatedByString
获取字符串元素数组。然后你最终可以使用flatMap
来创建一个整数数组。
例如:
let yourString = "[1, 0, 4]"
// trim off the start and end brackets of the string – then obtain an array of elements by using componentsSeparatedByString
let arrayOfStrings = yourString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]")).componentsSeparatedByString(", ")
// flatMap the arrayOfStrings to an array of integers, filtering out any strings that cannot be represented as numbers
let arrayOfInts = arrayOfStrings.flatMap{Int($0)}
print(arrayOfInts)
答案 1 :(得分:1)
试试这个:
var test = "[1, 0, 4]"
test = test.substringToIndex(test.endIndex.advancedBy(-1)).substringFromIndex(test.startIndex.advancedBy(1))
var result = test.componentsSeparatedByString(", ").flatMap {Int($0)}
print(result) // [1, 0, 4]