Swift中的'x?.y'与'x'相同吗?接着'.y'?

时间:2014-10-04 20:07:40

标签: syntax swift member optional

我理解在Swift中,如果我定义

var opt:String? = "Optional"

如果我尝试

,我会收到错误
opt.isEmpty 

因为opt属于String?类型,但没有isEmpty方法。我以为我明白了

opt?.isEmpty

不会产生错误,因为opt?解包(任何非nilopt,导致String,其中有isEmpty方法。但是

opt?

本身导致String?而不是String

?.?后面跟.的运算符不同吗?


尝试

(opt?).isEmpty 

并发出暗示性错误。

2 个答案:

答案 0 :(得分:2)

是的opt?.isEmptyString?不同。它被称为optional chaining。来自swift编程指南:

  

您可以在后面放置一个问号(?)来指定可选链接   您希望调用属性,方法或的可选值   如果可选的是非零,则下标。这与放置非常相似   一个感叹号(!)后面的可选值强制   解开它的价值。主要区别在于可选链接   当optional是nil时,优先失败,而强制解包   当optional为nil时触发运行时错误。

这会在您思考时创建可选项      var opt:String?

现在

 opt?.isEmpty //it will not crash if opt is nil 

相同
opt!.isEmpty //it will crash if opt is nil 

如果opt!nil而不是在运行时不会崩溃。可选链接用于调用长序列的可选而不调用。每个可选链返回可选,即?返回可选的unwraps它,如果nil不调用isEmpty,则调用isEmpty并重新输入value。 还

  (opt?).isEmpty 

当您编写上述语句时,它只是可选的(不是可选的可选项)并且由于大括号而无法解包。因此显示错误

$T2?? does not have a member named `isEmpty`

打开它使用

(opt?)!.isEmpty

它将返回false

修改:澄清更多

   var o1 = opt?
   var o2 = ((opt?)?)

它本身什么也不做,只是将相同的值分配给o1o2,即String?。 要解包opto1o2它们都是可选的,需要单!运算符来解包它。

另外请不要在String?opt?之间误解他们两者有何不同?在decleration中使用某种类型后,它会使它成为可选项,并且在变量?之后使用opt时,它用于在可选链接中展开并返回可选值,它将返回

额外的东西:

试着这样澄清

(((opt?)?)!).isEmpty     //it will unwrap with single !
((((opt?)?)!)?).isEmpty   //compiler will show suggestion to remove ?

以下语句使可选的

可选
   var opt:String??? = "Optional"

打开

   opt!!!.isEmpty

<强> EDIT2

opt?总是返回可选,但如果opt被定义为String!它是implicit optionalopt?将返回optional(explicit)。但如果opt已经是可选的opt?将无效

来自swift编程指南

  

换句话说:

If the type you are trying to retrieve is not optional, it will become optional because of the optional chaining.
If the type you are trying to retrieve is already optional, it will not become more optional because of the chaining.
     

因此:

If you try to retrieve an Int value through optional chaining, an Int? is always returned, no matter how many levels of chaining are used.
Similarly, if you try to retrieve an Int? value through optional chaining, an Int? is always returned, no matter how many levels of chaining are used.

答案 1 :(得分:1)

  

但是选择?在它自己的结果字符串?而不是一个字符串。

是。根据Swift语言参考,表达式,后缀表达式,Optional-Chaining Expression

  

就其本身而言,后缀? operator只是返回它的值   参数作为可选参数。

因此,将?单独放在可选的末尾是一个完整的无操作。它没有效果。

  是吗?一个不同的运营商?接着是。?

是。更具体地说,?在任何&#34;后缀表达式&#34;中使用optional-chaining effect,包括后跟()(函数调用),.(成员)访问)和[](下标)。