标签中的Swift可选 [英] Swift optional in label
问题描述
我在这里有此代码
let fundsreceived = String(stringInterpolationSegment: self.campaign?["CurrentFunds"]!)
cell.FundsReceivedLabel.text = "$\(funds received)"
正在打印Optional(1000)
我已经将!
添加到了变量中,但是可选选项并没有消失.知道我在这里做错了什么吗?
I have already added !
to the variable but the optional isn't going away. Any idea what have i done wrong here?
推荐答案
之所以发生这种情况,是因为您要传递给的参数
This is happening because the parameter you are passing to
String(stringInterpolationSegment:)
是可选.
是的,您做了
force unwrap
,但您仍然有Optional
...
Yes, you did a
force unwrap
and you still have anOptional
...
如果您分解行,请保留...
Infact if you decompose your line...
let fundsreceived = String(stringInterpolationSegment: self.campaign?["CurrentFunds"]!)
转换为以下等效语句...
into the following equivalent statement...
let value = self.campaign?["CurrentFunds"]! // value is an Optional, this is the origin of your problem
let fundsreceived = String(stringInterpolationSegment: value)
您发现value
是Optional
!
- 因为
self.campaign?
产生和Optional
- 然后
["CurrentFunds"]
产生另一个Optional
- 最后,你的部队
unwrap
撤出一个Optional
- Because
self.campaign?
produces anOptional
- Then
["CurrentFunds"]
produces anotherOptional
- Finally your force
unwrap
removes oneOptional
因此 2个可选- 1个可选 = 1个可选
首先是我能找到的最丑陋的解决方案
我正在编写此解决方案只是为了告诉您您应该不要做什么.
let fundsreceived = String(stringInterpolationSegment: self.campaign!["CurrentFunds"]!)
如您所见,我用强制展开!
替换了您的条件展开?
.只是不要在家做!
As you can see I replaced your conditional unwrapping ?
with a force unwrapping !
. Just do not do it at home!
请记住,您应该尽可能避免使用此人!
!
Remember, you should avoid this guy !
everytime you can!
if let
campaign = self.campaign,
currentFunds = campaign["CurrentFunds"] {
cell.FundsReceivedLabel.text = String(stringInterpolationSegment:currentFunds)
}
- 在这里,我们使用
conditional binding
将可选的self.campaign
转换为non optional
常量(如果可能). - 然后我们将
campaign["CurrentFunds"]
的值转换为non optional type
(如果可能).
- Here we are using
conditional binding
to transform the optionalself.campaign
into anon optional
constant (when possible). - Then we are transforming the value of
campaign["CurrentFunds"]
into anon optional type
(when possible).
最后,如果IF成功,我们可以放心使用currentFunds
,因为它不是可选的.
Finally, if the IF does succeed, we can safely use currentFunds
because it is not optional.
希望这会有所帮助.
这篇关于标签中的Swift可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!