swift 选项的快速枚举

swift fast enumeration of optionals

有更好的方法吗?语法上看起来更好的东西?

let a : [Any] = [5,"a",6]
for item in a { 
  if let assumedItem = item as? Int {
     print(assumedItem) 
  } 
}

类似这样,但语法正确吗?

  for let item in a as? Int { print(item) }

如果您使用 Swift 2:

let array: [Any] = [5,"a",6]

for case let item as Int in array {
    print(item)
}

两种解决方案

let a = [5,"a",6]

a.filter {[=10=] is Int}.map {print([=10=])}

for item in a where item is Int {
    print(item)
}

实际上数组中根本没有可选项

您也可以使用 flatMap 将数组转换为 [Int]

let a : [Any] = [5,"a",6]
for item in a.flatMap({ [=10=] as? Int }) {
    print(item)
}

使用Swift5,您可以选择以下Playground示例代码之一来解决您的问题。


#1。使用 as type-casting pattern

let array: [Any] = [5, "a", 6]

for case let item as Int in array {
    print(item) // item is of type Int here
}

/*
 prints:
 5
 6
 */

#2。使用 compactMap(_:) 方法

let array: [Any] = [5, "a", 6]

for item in array.compactMap({ [=11=] as? Int }) {
    print(item) // item is of type Int here
}

/*
 prints:
 5
 6
 */

#3。使用 where 子句和 is type-casting pattern

let array: [Any] = [5, "a", 6]

for item in array where item is Int {
    print(item) // item conforms to Any protocol here
}

/*
 prints:
 5
 6
 */

#4。使用 filter(_:​) 方法

let array: [Any] = [5, "a", 6]

for item in array.filter({ [=13=] is Int }) {
    print(item) // item conforms to Any protocol here
}

/*
 prints:
 5
 6
 */