Swift-从数组中修剪元素,将整数字符串转换为整数 [英] Swift - pruning elements from an Array, converting integer strings to integers
问题描述
我有一个包含数字和空字符串的数组,例如["", "2", "4", "", "", "1", "2", ""]
.我想将其简化为一个数字列表,例如[2,4,1,2]
.
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?
推荐答案
借助Swift 2,我们可以利用flatMap
和Int()
的优势:
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]
说明:如果字符串不包含整数,则Int()
返回nil
,并且flatMap
忽略nil
并解包Int()
返回的可选Int
.
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()
.
这篇关于Swift-从数组中修剪元素,将整数字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!