作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
有更好的方法吗?语法上看起来更好的东西?
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 5,您可以选择以下 Playground 示例代码之一来解决您的问题。
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
*/
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
*/
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
*/
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
*/
关于swift 快速枚举选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32562235/
我是一名优秀的程序员,十分优秀!