标签中的Swift可选 [英] Swift optional in label

查看:72
本文介绍了标签中的Swift可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有此代码

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 an Optional...

如果您分解行,请保留...

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)

您发现valueOptional

  1. 因为self.campaign? 产生Optional
  2. 然后["CurrentFunds"] 产生另一个Optional
  3. 最后,你的部队unwrap 撤出一个Optional
  1. Because self.campaign? produces an Optional
  2. Then ["CurrentFunds"] produces another Optional
  3. Finally your force unwrap removes one Optional

因此 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)
}

  1. 在这里,我们使用conditional binding将可选的self.campaign转换为non optional常量(如果可能).
  2. 然后我们将campaign["CurrentFunds"]的值转换为non optional type(如果可能).
  1. Here we are using conditional binding to transform the optional self.campaign into a non optional constant (when possible).
  2. Then we are transforming the value of campaign["CurrentFunds"] into a non optional type (when possible).

最后,如果IF成功,我们可以放心使用currentFunds,因为它不是可选的.

Finally, if the IF does succeed, we can safely use currentFunds because it is not optional.

希望这会有所帮助.

这篇关于标签中的Swift可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆