小编You*_*jen的帖子

Swift:调用可选变量的方法

所以我知道'!'之间的区别 和'?',我只是想知道在调用可选变量的方法时使用它们的最佳方法是什么

var bar: Bar? = nil

bar?.doSomething()  // this will be valid, but wouldn't call doSomething
bar!.doSomething() // Given error: EXC_BAD_INSTRUCTIONS (Obviously)
Run Code Online (Sandbox Code Playgroud)

但是当'bar'不是nil时,这两个方法调用都是有效的.

bar = Bar()
bar?.doSomething()  // Valid
bar!.doSomething()  // Valid
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,调用可选变量方法的最佳方法是什么,我个人使用:

if bar != nil {
    bar!.doSomething()
}
Run Code Online (Sandbox Code Playgroud)

还是会吧?.doSomething()做同样的事情?

swift optional-operator

13
推荐指数
2
解决办法
3955
查看次数

标签 统计

optional-operator ×1

swift ×1