gpt4 book ai didi

swift 快速枚举选项

转载 作者:搜寻专家 更新时间:2023-10-30 22:31:00 24 4
gpt4 key购买 nike

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

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 示例代码之一来解决您的问题。


#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({ $0 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({ $0 is Int }) {
print(item) // item conforms to Any protocol here
}

/*
prints:
5
6
*/

关于swift 快速枚举选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32562235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com