我有以下代码:
var data = [12,33,22,44];
var a = data.description; // results is "[12,33,22,44]"
var new = Array(a); // result is ['[','1'. not [12,33,22,44]
除了拆分'a'并迭代结果外,还有一种将字符串转换为数组的最快方法吗?
由于
答案 0 :(得分:4)
您可以通过拆分数组并过滤所有无法转换为Int
的元素来实现。
"[12,33,22,44]".componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "[,]")).filter{ $0.toInt() != nil }.map{ $0.toInt()! } // [12, 33, 22, 44]
答案 1 :(得分:3)
你可以
[
; ]
和stringByTrimmingCharactersInSet
个字符
例如:
let array = [12,33,22,44];
let string = array.description; // result is "[12, 33, 22, 44]", not "[12,33,22,44]"
let results = string
.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]"))
.componentsSeparatedByString(",")
.map { return $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) }
或者如果你想要一个整数数组而不是一个字符串数组:
let results = string
.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]"))
.componentsSeparatedByString(",")
.map { return $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).toInt()! } // remove `!` if you're not assured that only integers will be present
答案 2 :(得分:1)
这样做的一种安全方法是将String编码为数据,然后将数据解码为JSON,最后将结果转换为Ints数组:
let base = [12,33,22,44]
let source = base.description
if let data = source.dataUsingEncoding(NSUTF8StringEncoding) {
if let arrayOfInts = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [Int] {
print(arrayOfInts) // [12, 33, 22, 44]
print(arrayOfInts[1]) // 33
}
}
答案 3 :(得分:0)
Rob对Swift 2.2的回答
let results = value
.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]"))
.componentsSeparatedByString(",")
.map { return Int($0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()))!} // remove `!` if you're not assured that only integers will be present
答案 4 :(得分:0)
Swift 3代码:
let results = "[12,33,22,44]"
.trimmingCharacters(in: CharacterSet(charactersIn: "[]"))
.components(separatedBy:",")
print("Result array: \(results)")