gpt4 book ai didi

swift - swift 是否具有像 Kotlin 那样的标准(范围)功能?

转载 作者:IT老高 更新时间:2023-10-28 13:46:53 26 4
gpt4 key购买 nike

在 Kotlin 中,我们有一个列表 standard (scope) functions (例如 letapplyrun 等)

下面的使用示例

val str : String? = "123"
str?.let{ print(it) }

这使得代码看起来更简洁,无需if (str != null)

在swift中,我将其编码如下

let str: String? = "123"
if str != nil { print(str!) }

我必须有 if str != nil。是否有默认提供的 let 可供我使用(无需我自己编写)?

仅供引用,我是 Swift 新手,四处检查似乎找不到它。

最佳答案

如果你喜欢 if,扩展 Optional 的功能

extension Optional {
func `let`(do: (Wrapped)->()) {
guard let v = self else { return }
`do`(v)
}
}

var str: String? = "text"
str.let {
print( $0 ) // prints `text`
}
str = nil

str.let {
print( $0 ) // not executed if str == nil
}

关于swift - swift 是否具有像 Kotlin 那样的标准(范围)功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54966200/

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