Swift - pruning elements from an Array, converting integer strings to integers

纵然是瞬间 提交于 2019-12-24 06:22:07

问题


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 nils and unwraps the optional Ints 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!