Swift optional in label

对着背影说爱祢 提交于 2019-12-12 09:27:30

问题


I have this code right here

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

It is printing out Optional(1000)

I have already added ! to the variable but the optional isn't going away. Any idea what have i done wrong here?


回答1:


This is happening because the parameter you are passing to

String(stringInterpolationSegment:)

is an 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)

you find out that value is an Optional!

Why?

  1. Because self.campaign? produces an Optional
  2. Then ["CurrentFunds"] produces another Optional
  3. Finally your force unwrap removes one Optional

So 2 Optionals - 1 Optional = 1 Optional

First the ugliest solution I can find

I am writing this solution just to tell you what you should NOT do.

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!

Now the good solution

Remember, you should avoid this guy ! everytime you can!

if let
    campaign = self.campaign,
    currentFunds = campaign["CurrentFunds"] {
        cell.FundsReceivedLabel.text = String(stringInterpolationSegment:currentFunds)
}
  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).

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

Hope this helps.




回答2:


Unwrap it with if let this way:

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

Look at this simple example:

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

But if you declare it as an optional like this:

let abc:String? = "AnyString"

now you can unwrap it without any error like this:

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

Hope this example will help.



来源:https://stackoverflow.com/questions/31939516/swift-optional-in-label

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!