所以,如果我有一个字符串数组,并且我想提取所有整数(如String
s),我该怎么做?
例如:
myArray = ["1","2","3","unknown","bob"]
我试过
myArray.filter { Int($0) }
但我收到错误消息,告诉我我无法将Int?
转换为Bool
答案 0 :(得分:1)
你几乎拥有它。
Swift 3
let filteredArray = myArray.filter { Int($0) != nil }
答案 1 :(得分:1)
简单地说,就像这样:
let myArray = ["1","2","3","unknown","bob"]
let filteredArray = myArray.filter { Int($0) != nil }
print(filteredArray) // ["1", "2", "3"]
请注意,filteredArray
为[String]
。要将其设为[Int]
,您应该使用 map :
let filteredArray = myArray.filter { (Int($0) != nil) }.map { Int($0)! }
print(filteredArray) // [1, 2, 3]
答案 2 :(得分:1)
如果您只想保留可以成功转换的整数,请使用flatMap
:
let strings = ["1", "2", "3", "unknown", "bob"]
let numbers = strings.flatMap{ Int($0) } // => [1, 2, 3]