Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift string from optional Double

Tags:

swift

Is there a shortcut to specify placeholder text when the value is nil in Swift?

Right now I do:

let myText:String!
if myDouble != nil{
  myText = "\(myDouble!)"
}else{
  myText = "Value not provided"
}

That works, but it's very annoying to have to do that all the time. Is there a way to do something like

let myText:String = "\(myDouble ?? "Value no provided")"

That fails because it wants a default Double value, but I really want a String value.

like image 893
Running Buffalo Avatar asked Aug 06 '26 11:08

Running Buffalo


1 Answers

You can use map and nil-coalescing:

let myText = myDouble.map { String($0) } ?? "Value not provided"

If myDouble is nil, the result of map is nil and the result is the value after the ??.

If myDouble is not nil, the result is the output of the map which creates a string from the Double.

For more details, please see the documentation for the map function of the Optional enumeration in the Swift standard library.

like image 121
rmaddy Avatar answered Aug 10 '26 20:08

rmaddy