问题
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 unwrapand 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)
you find out that value is an Optional!
Why?
- Because
self.campaign?produces anOptional - Then
["CurrentFunds"]produces anotherOptional - Finally your force
unwrapremoves oneOptional
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)
}
- Here we are using
conditional bindingto transform the optionalself.campaigninto anon optionalconstant (when possible). - Then we are transforming the value of
campaign["CurrentFunds"]into anon 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