How do I prevent my text from displaying Optional() in the Swift interpolation?
My text displaying is :
---You can only switch properties once all images from Op
Swift is doing this because you provided an optional string, not a string. To solve it you need to unwrap the optional.
You can either use ! to unwrap an optional string, such as:
messageText.text = "You can only switch properties once all images\(propertyNameStr!) have finished uploading."
Or you can use a if statement to unwrap the optional.
if let nameString = propertyNameStr {
messageText.text = "You can only switch properties once all images\(nameString) have finished uploading."
}
I ended up going with the following because I didn't want to use guard, but I wanted to always display the message:
var propertyNameStr = ""
if let propertyName = syncer!.getPropertyConfig()?.propertyName {
propertyNameStr = "from \(propertyName) "
}
messageText.text = "You can only switch properties once all images \(propertyNameStr)have finished uploading."
Use optional binding to safely unwrap the optionals, then use String interpolation on the non-optional value.
guard let imagesLeftToUpload = syncer?.imagesToUpload?.count, imagesLeftToUpload > 0 else {return}
guard let propertyConfig = syncer?.getPropertyConfig(), let propertyName = propertyConfig.propertyName else {return}
messageText.text = "You can only switch properties once all images\(propertyName) have finished uploading."