有更好的方法吗?有什么更好的语法吗?
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) }发布于 2017-03-17 16:41:26
使用Swift 5,您可以选择下列游乐场示例代码之一以解决您的问题。
#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
*/#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
*/#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
*/#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
*/发布于 2015-09-14 10:18:41
如果你使用Swift 2:
let array: [Any] = [5,"a",6]
for case let item as Int in array {
print(item)
}发布于 2015-09-14 10:23:42
两解
let a = [5,"a",6]
a.filter {$0 is Int}.map {print($0)}或
for item in a where item is Int {
print(item)
}实际上,数组中根本没有选项。
https://stackoverflow.com/questions/32562235
复制相似问题