迅速列举的期权

use*_*972 5 optional fast-enumeration swift

有没有更好的方法来做到这一点?看起来更好的语法明智的东西?

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

这样的东西,然后用正确的语法?

  for let item in a as? Int { print(item) }
Run Code Online (Sandbox Code Playgroud)

ABa*_*ith 6

如果您使用的是Swift 2:

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

for case let item as Int in array {
    print(item)
}
Run Code Online (Sandbox Code Playgroud)


Ima*_*tit 5

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


#1. 使用as 类型转换模式

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
 */
Run Code Online (Sandbox Code Playgroud)

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

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

for item in array.compactMap({ $0 as? Int }) {
    print(item) // item is of type Int here
}

/*
 prints:
 5
 6
 */
Run Code Online (Sandbox Code Playgroud)

#3. 使用 where 子句和is 类型转换模式

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
 */
Run Code Online (Sandbox Code Playgroud)

#4. 使用filter(_:?)方法

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

for item in array.filter({ $0 is Int }) {
    print(item) // item conforms to Any protocol here
}

/*
 prints:
 5
 6
 */
Run Code Online (Sandbox Code Playgroud)