问题
I have an array that contains numbers and empty strings, like ["", "2", "4", "", "", "1", "2", ""]
. I would like to pare this down to a list of numbers, like [2,4,1,2]
.
My first effort split this into two steps, first strip out the empty strings, then do the string-to-integer conversion. However, my code for step one isn't working as desired.
for (index,value) in tempArray.enumerate(){
if value == "" {
tempArray.removeAtIndex(index)
}
}
This fails, I believe because it is using the index values from the original, complete array, though after the first deletion they are not longer accurate.
What would be a better way to accomplish my goal, and what is the best way to convert the resulting array of integer strings to an array of integers?
回答1:
With Swift 2 we can take advantage of flatMap
and Int()
:
let stringsArray = ["", "2", "4", "", "", "1", "2", ""]
let intsArray = stringsArray.flatMap { Int($0) }
print(intsArray) // [2, 4, 1, 2]
Explanation: Int()
returns nil
if the string does not contain an integer, and flatMap
ignores nil
s and unwraps the optional Int
s returned by Int()
.
回答2:
var str = ["", "2", "4", "", "", "1", "2", ""]
let filtered = str.filter {$0 != "" }
let intArr = filtered.map {($0 as NSString).integerValue}
来源:https://stackoverflow.com/questions/32876166/swift-pruning-elements-from-an-array-converting-integer-strings-to-integers