Swift 标签可选

Swift optional in label

我这里有这个代码

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

打印出来Optional(1000)

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

if let这样解开它:

if let fundsreceived = String(stringInterpolationSegment: self.campaign?["CurrentFunds"]!){
    cell.FundsReceivedLabel.text = "$\(fundsreceived)"
}

看这个简单的例子:

let abc:String = "AnyString"  //here abc is not an optional

if let cde = abc {           //So you will get error here  Bound value in a conditional binding must be of optional type 
    println(cde)
}

但是如果你像这样将它声明为可选的:

let abc:String? = "AnyString"

现在你可以像这样打开它而不会出现任何错误:

if let cde = abc {
    println(cde)    //AnyString
}

希望这个例子对您有所帮助。

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

String(stringInterpolationSegment:)

是一个可选

Yes, you did a force unwrap and you still have an Optional...

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

let fundsreceived = String(stringInterpolationSegment: self.campaign?["CurrentFunds"]!)

进入以下等效语句...

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

你发现 value 是一个 Optional!

为什么?

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

So 2 Optionals - 1 Optional = 1 Optional

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

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

let fundsreceived = String(stringInterpolationSegment: self.campaign!["CurrentFunds"]!)

如您所见,我用强制展开 ! 替换了条件展开 ?。只是不要在家里做!

现在是好的解决方案

记住,你应该尽可能避开这个人!

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(如果可能的话)。

最后,如果 IF 确实成功了,我们可以安全地使用 currentFunds,因为它不是可选的。

希望这对您有所帮助。