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)
如果您使用的是Swift 2:
let array: [Any] = [5,"a",6]
for case let item as Int in array {
print(item)
}
Run Code Online (Sandbox Code Playgroud)
使用 Swift 5,您可以选择以下 Playground 示例代码之一来解决您的问题。
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)
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)
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)
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)
| 归档时间: |
|
| 查看次数: |
4286 次 |
| 最近记录: |