Swift optional in label
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 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
unwrap
removes 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 binding
to transform the optionalself.campaign
into anon optional
constant (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.
Unwrapping an Optional value for a Label
You are force unwrapping an optional by adding a !
, so if the value is null like it is in your case the program will crash.
To unwrap an optional in a safe way (for a generic case) follow this method from Hacking With Swift:
var name: String? = nil
if let unwrapped = name {
print("\(unwrapped.count) letters")
} else {
print("Missing name.")
}
In your SPECIFIC case however verifiedLabel
is likely your label set on a storyboard. So you can unwrap it like var verifiedLabel:UILabel!
since the value should NOT be null.
So now since its null, a) please check your outlet connections and if everything looks good b) check this thread for debugging: IBOutlet is nil, but it is connected in storyboard, Swift
UIlabel text does not show optional word when setting optional text?
The text
property of UILabel
is optional. UILabel
is smart enough to check if the text
property's value is set to nil
or a non-nil value. If it's not nil
, then it shows the properly unwrapped (and now non-optional) value.
Internally, I imagine the drawRect
method of UILabel
has code along the lines of the following:
if let str = self.text {
// render the non-optional string value in "str"
} else {
// show an empty label
}
How do I remove optional text from UILabel
I would recommend Nil-Coalescing Operator ( ?? ). You can find detailed info here
class Test {
var ibu: Double?
}
var tt: Test? = Test()
tt?.ibu = 3.14
print(String(describing: tt?.ibu)) // Optional("3.14")
print(tt?.ibu ?? 0) // 3.14
tt?.ibu = nil
print(String(describing: tt?.ibu)) // nil
print(tt?.ibu ?? 0) // 0
Why is my label displaying Your cat is Optional(35) years old when it should display Your cat is 35 years old?
The problem is here:
String(describing: catYears)
catYears
is an Optional<Int>
, a string that describes an Optional<Int>
will be in the format of Optional(<value>)
or nil
. That's why you get Optional(35)
.
You need to unwrap catYears
!
String(describing: catYears!)
Or, remove String(describing:)
all together and do:
if let humanYearsText = getHumanYears.text, let humanYears = Int(humanYearsText)
{
let catYears = humanYears * 7
displayCatYears.text = "Your cat is \(catYears) years old"
}
Showing optional double number on a label
Use if let
to unwrap optional values:
let row = elementArray[indexPath.row]
if let myNumber = row.meltPoint {
mPoint.text = "\(myNumber)"
} else {
mPoint.text = "N/A"
}
Related Topics
Custom Annotation Showing Same Image for All Different Types of Poi'S
How to Restrict an Enum to Certain Cases of Another Enum
Behaviour of Protocols with Self
How to Use Nsvisualeffectview to Blend Window with Background
How to Add Document with Custom Id to Firebase (Firestore) on Swift
Swift Compilation Time with Nil Coalescing Operator
How to Set an Initial Value for @Nsmanaged Property Pfobject Subclass
How to Call a Selector-Based Timer Method on a Swift Struct
Swift Convenience Initializer Extension for Skphysicsbody
Spritekit Skphysicsjointfixed Odd Behaviour
Adding Index List and Section Headers to Translated Tableview
How to Switch to Swift 4.0 in Xcode 9.3
How to Use Willset and Didset with Getter and Setter
How Would I Create a Constant That Could Be One of Several Strings Depending on Conditions
Applewatch Messages Url Works Hard Coded But Not with Variables
Timer Not Firing Every Second on Watchkit