标签中的Swift可选

Exc*_*ons 0 optional swift

我在这里有这个代码

let fundsreceived = String(stringInterpolationSegment: self.campaign?["CurrentFunds"]!)
cell.FundsReceivedLabel.text = "$\(funds received)"
Run Code Online (Sandbox Code Playgroud)

它正在打印出来 Optional(1000)

我已经添加!到变量但是可选项不会消失.知道我在这里做错了什么吗?

Luc*_*tti 6

发生这种情况是因为您要传递的参数

String(stringInterpolationSegment:)
Run Code Online (Sandbox Code Playgroud)

是一个可选的.

是的,你做了一个force unwrap,你仍然有Optional......

事实上,如果你分解你的线...

let fundsreceived = String(stringInterpolationSegment: self.campaign?["CurrentFunds"]!)
Run Code Online (Sandbox Code Playgroud)

进入以下等同声明......

let value = self.campaign?["CurrentFunds"]! // value is an Optional, this is the origin of your problem
let fundsreceived = String(stringInterpolationSegment: value)
Run Code Online (Sandbox Code Playgroud)

你发现那value是一个Optional!

为什么?

  1. 因为self.campaign? 产生Optional
  2. 然后["CurrentFunds"] 生产另一个Optional
  3. 最后你的力量unwrap 会移除一个Optional

所以2个选项 - 1个可选 = 1个可选

首先,我能找到最丑陋的解决方案

我写这个解决方案只是为了告诉你,你应该什么这样做.

let fundsreceived = String(stringInterpolationSegment: self.campaign!["CurrentFunds"]!)
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我?用力展开取代了你的条件展开!.只是不要在家里做!

现在是好的解决方案

记住,你应该!每次都避免这个家伙!

if let
    campaign = self.campaign,
    currentFunds = campaign["CurrentFunds"] {
        cell.FundsReceivedLabel.text = String(stringInterpolationSegment:currentFunds)
}
Run Code Online (Sandbox Code Playgroud)
  1. 这里我们conditional binding用来将可选项self.campaign转换为non optional常量(如果可能).
  2. 然后我们将值campaign["CurrentFunds"]转换为a non optional type(如果可能的话).

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

希望这可以帮助.