Types 从列表中选择特定类型的项目
给定一个集合或数组,如Types 从列表中选择特定类型的项目,types,filter,swift2,Types,Filter,Swift2,给定一个集合或数组,如[1,2,3,“x”]或[“1”、“2”、“3”、“x”],如何最好地提取(可能使用.filter)整数(例如)。在上面的任何一个例子中,我希望得到答案[1,2,3]对于混合阵列,我会使用过滤器和is: let hybrid = [1,2,3,"x"] let ints = hybrid.filter { $0 is Int } print(ints) // [1, 2, 3] 对于字符串数组,我将使用flatMap和Int初始值设定项: let strings =
[1,2,3,“x”]
或[“1”、“2”、“3”、“x”]
,如何最好地提取(可能使用.filter)整数(例如)。在上面的任何一个例子中,我希望得到答案[1,2,3]
对于混合阵列,我会使用过滤器
和is
:
let hybrid = [1,2,3,"x"]
let ints = hybrid.filter { $0 is Int }
print(ints) // [1, 2, 3]
对于字符串数组,我将使用flatMap
和Int
初始值设定项:
let strings = ["1","2","3","x"]
let ints = strings.flatMap { Int($0) }
print(ints) // [1, 2, 3]