2017-02-20 114 views
0

我最近遇到了这个代码片段。嵌套合并运算符的混淆

let s1: String?? = nil 
(s1 ?? "inner") ?? "outer" // Prints inner 





let st2: String?? = .some(nil) 
(st2 ?? "inner") ?? "outer" // prints outer 

不知道为什么(s2 ?? "inner")返回nil。完全困惑于此。有人能帮我理解原因吗?

回答

2

最初不顾结合使用nil合并运算符的:与嵌套可选类型的工作(由于某种原因)时,它可以帮助明确打出来的类型(而不是使用普通?语法糖每个可选“水平”)。例如: -

let s1: Optional<Optional<String>> = nil 
    /* ^^^^^^^^^................^- 'nil' with regard to "outer" optional */ 

let s2: Optional<Optional<String>> = .some(nil) 
    /* ^^^^^^^^^................^- the "outer" optional has value .some(...), i.e, 
            not 'nil' which would be .none. 
       ^^^^^^^^^^^^^^^^-the "inner" optional, on the other hand, has 
            value 'nil' (.none) */ 

使用显式类型嵌套可选(String??)和分析如上两种不同的任务,我们就可以着手评估两者结合nil合并运算上的每个实例调用。显而易见的是:

let foo1 = (s1 ?? "inner") ?? "outer" // equals "inner" 
     /* ^^- is 'nil', hence the call to 's1 ?? "inner" will coalesce 
       to "inner", which is a concrete 'String' (literal), which 
       means the second nil coalescing operator will not coelesce 
       to "outer" */ 

let foo2 = (s2 ?? "inner") ?? "outer" // equals "outer" 
     /* ^^- is .some(...), hence the call to 's1 ?? "inner" will coalesce 
       to _the concrete value wrapped in 's1'_; namely 'nil', due some, .some(nil). 
       hence, (s1 ?? "inner") results in 'nil', whereafter the 2nd nil 
       coalescing call, 'nil ?? "outer"', will naturally result in 'outer' */ 

对理解略微棘手s2情况下的关键是与LHS施加nil合并运算符(左手侧)即.some(...)将总是导致在由包裹值即使包装值本身恰巧是nil(或.none),也是如此。

Optional<SomeType>.some(someThing) ?? anotherThing 
// -> someThing, even if this happens to be 'nil' 

这也很明显,如果我们选择看看the stdlib implementation of the nil coalescing operator

public func ?? <T>(optional: T?, defaultValue: @autoclosure() throws -> T) 
    rethrows -> T { 
    switch optional { 
    case .some(let value): 
    // in your example (s2 and leftmost ?? call), 'T' is Optional<String>, 
    // and 'value' will have the value 'nil' here (which is a valid return for 'T') 
    return value 
    case .none: 
    return try defaultValue() 
    } 
} 
+0

我认为有在代码的第二块的错误,因为这两个foo1和foo2的声明同样存在。不应该是“foo2 =(s2 ?? ...”? – nbloqs

+0

@nbloqs是的,谢谢,代表我的错字! – dfri

+0

我很乐意帮忙! – nbloqs

2
let st2: String?? = .some(nil) 
(st2 ?? "inner") ?? "outer" // prints outer 

不知道为什么(S2 ?? “内部”)返回nil

因为这是你放在那里:

let st2: String?? = .some(nil) 
          ^^^ 

比较:

let st2: String?? = .some("howdy") 
(st2 ?? "inner") ?? "outer" // prints howdy