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

Ely*_*lye 5 kotlin swift

在科特林我们有一个列表标准(范围)功能(例如letapplyrun等)

下面的用法示例

val str : String? = "123"
str?.let{ print(it) }
Run Code Online (Sandbox Code Playgroud)

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

很快,我将其编码如下

let str: String? = "123"
if str != nil { print(str!) }
Run Code Online (Sandbox Code Playgroud)

我必须有if str != nillet默认情况下是否有我可以使用的提供程序(无需自己编写)?

仅供参考,我是Swift的新手,但检查似乎找不到它。

use*_*734 6

如果您愿意,请扩展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
}
Run Code Online (Sandbox Code Playgroud)

  • 这与使用不同名称的https://developer.apple.com/documentation/swift/optional/1539476-map基本上不是相同的吗? (3认同)
  • 这不会像Optional.map那样“转换”任何东西。在您的示例中,它转换为Void,因此仅被“蒙版”。`public func map <U>(_ transform:(Wrapped)throws-> U)rethrows-> U? (2认同)

iel*_*ani 4

你可以使用Optional.map

let str1 : String? = "123"
str1.map { print($0) }
Run Code Online (Sandbox Code Playgroud)

印刷123

let str2 : String? = nil
str2.map { print($0) }
Run Code Online (Sandbox Code Playgroud)

不打印任何东西。

因此,如果可选值不是nil,它将被解包并用作闭包的参数map。如果没有,则不会调用闭包。


swift 中更惯用的方法是使用可选绑定:

var str: String? = "123"
if let s = str { 
    print(s) 
}
Run Code Online (Sandbox Code Playgroud)

  • 这在技术上实现了OP的要求,但似乎与“地图”的意图(即转换值)和功能遗产不一致。我个人不会建议这种模式...... (2认同)