为什么我不能调用 map<U>(_ transform: (Wrapped) -> U) -> U?并同时使用可选链接?
Why can't I call map<U>(_ transform: (Wrapped) -> U) -> U? and use optional chaining at the same time?
我知道像这样的可选链接:
someOptional?.someProperty
基本上是
someOptional.map { [=12=].someProperty }
然而,我发现同时做这两件事是不可能的:
// someOptional?.someProperty evaluates to an optional type, right?
// so the map method should exist!
someOptional?.someProperty.map(someClosure) // can't find "map"
这是一个 MCVE:
let s: String? = "Hello"
s?.hashValue.map(Double.init)
我认为写类似上面的东西比:
更具可读性
s.map { Double([=15=].hashValue) }
所以我非常想要一种同时使用可选链接和 map
的方法。
我该怎么做?
显然,出于某种原因,将第一部分括在方括号中有效:
(s?.hashValue).map(Double.init)
我认为这在某种程度上是由于 ?
具有较低的优先级,或者可选链接与其他表达式的工作方式不同。添加括号可能会导致 s?.hashValue
成为表达式。
编辑:
以下是 Swift reference 的相关摘录:
If a postfix expression that contains an optional-chaining expression
is nested inside other postfix expressions, only the outermost
expression returns an optional type. In the example below, when c is
not nil, its value is unwrapped and used to evaluate .property, the
value of which is used to evaluate .performAction(). The entire
expression c?.property.performAction() has a value of an optional
type.
所以 s?.hashValue
实际上并不计算为可选类型,因为它嵌套在另一个表达式中。通过添加 ()
,我将它分成另一个表达式,手动使其计算为可选类型。
我知道像这样的可选链接:
someOptional?.someProperty
基本上是
someOptional.map { [=12=].someProperty }
然而,我发现同时做这两件事是不可能的:
// someOptional?.someProperty evaluates to an optional type, right?
// so the map method should exist!
someOptional?.someProperty.map(someClosure) // can't find "map"
这是一个 MCVE:
let s: String? = "Hello"
s?.hashValue.map(Double.init)
我认为写类似上面的东西比:
更具可读性s.map { Double([=15=].hashValue) }
所以我非常想要一种同时使用可选链接和 map
的方法。
我该怎么做?
显然,出于某种原因,将第一部分括在方括号中有效:
(s?.hashValue).map(Double.init)
我认为这在某种程度上是由于 ?
具有较低的优先级,或者可选链接与其他表达式的工作方式不同。添加括号可能会导致 s?.hashValue
成为表达式。
编辑:
以下是 Swift reference 的相关摘录:
If a postfix expression that contains an optional-chaining expression is nested inside other postfix expressions, only the outermost expression returns an optional type. In the example below, when c is not nil, its value is unwrapped and used to evaluate .property, the value of which is used to evaluate .performAction(). The entire expression c?.property.performAction() has a value of an optional type.
所以 s?.hashValue
实际上并不计算为可选类型,因为它嵌套在另一个表达式中。通过添加 ()
,我将它分成另一个表达式,手动使其计算为可选类型。