Running Buffalo
Running Buffalo

Reputation: 1323

Swift string from optional Double

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.

Upvotes: 2

Views: 2062

Answers (4)

Teejay
Teejay

Reputation: 7471

This should work:

let myText = myDouble != nil ? String(myDouble!) : "Value not provided"

Upvotes: 0

Dominik Bucher
Dominik Bucher

Reputation: 2169

I think good approach to this is to make Extension to optional where Double is the Wrapped element:

extension Optional where Wrapped == Double  {

    var stringValue: String {
        guard let me = self else { return "No Value Provided" }
        return "\(me)"
    }
}

// Use it like this:

myDouble.stringValue

Another approach could be making your custom operator like this:

public func ??(rhd: Double?, lhd: String) -> String {
    if let unwrapped = rhd {
        return String(unwrapped)
    } else {
        return lhd
    }
}

And now your line let myText:String = "\(myDouble ?? "Value no provided")" works. Please let me now if you don' understand anything.

Upvotes: 2

eirikvaa
eirikvaa

Reputation: 1146

It seems reasonable to do

let myDouble: Double? = Double(3.0)
let myText = myDouble?.description ?? "Value not provided"

If myDouble is nil, then myText is "Value not provided". If myDouble is not nil, it's assigned the string representation of the number.

Upvotes: 2

rmaddy
rmaddy

Reputation: 318774

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.

Upvotes: 7

Related Questions