How to convert Swift Bool? -> String?

SwiftCasting

Swift Problem Overview


Given a Bool?, I'd like to be able to do this:

let a = BoolToString(optbool) ?? "<None>"

which would either give me "true", "false", or "<None>".

Is there a built-in for BoolToString?

Swift Solutions


Solution 1 - Swift

String(Bool) is the easiest way.

var myBool = true
var boolAsString = String(myBool)

Solution 2 - Swift

let b1: Bool? = true
let b2: Bool? = false
let b3: Bool? = nil

print(b1?.description ?? "none") // "true"
print(b2?.description ?? "none") // "false"
print(b3?.description ?? "none") // "none"

or you can define 'one liner' which works with both Bool and Bool? as a function

func BoolToString(b: Bool?)->String { return b?.description ?? "<None>"}

Solution 3 - Swift

let trueString = String(true) //"true"
let trueBool = Bool("true")   //true
let falseBool = Bool("false") //false
let nilBool = Bool("foo")     //nil

Solution 4 - Swift

You could use the ?: ternary operator:

let a = optBool == nil ? "<None>" : "\(optBool!)"

Or you could use map:

let a = optBool.map { "\($0)" } ?? "<None>"

Of the two, optBool.map { "\($0)" } does exactly what you want BoolToString to do; it returns a String? that is Optional(true), Optional(false), or nil. Then the nil coalescing operator ?? unwraps that or replaces nil with "<None>".

Update:

This can also be written as:

let a = optBool.map(String.init) ?? "<None>"

or:

let a = optBool.map { String($0) } ?? "<None>"

Solution 5 - Swift

var boolValue: Bool? = nil
var stringValue = "\(boolValue)" // can be either "true", "false", or "nil"

Or a more verbose custom function:

func boolToString(value: Bool?) -> String {
    if let value = value {
        return "\(value)"
    }
    else { 
        return "<None>"
        // or you may return nil here. The return type would have to be String? in that case.
    }

}

Solution 6 - Swift

You can do it with extensions!

extension Optional where Wrapped == Bool {
  func toString(_ nilString: String = "nil") -> String {
    self.map { String($0) } ?? nilString
  }
}

Usage:

let b1: Bool? = true
let b2: Bool? = false
let b3: Bool? = nil

b1.toString() // "true"
b2.toString() // "false"

b3.toString() // "nil"
b3.toString("<None>") // "<None>"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnaView Question on Stackoverflow
Solution 1 - SwiftRandom Swift UserView Answer on Stackoverflow
Solution 2 - Swiftuser3441734View Answer on Stackoverflow
Solution 3 - SwiftElijahView Answer on Stackoverflow
Solution 4 - SwiftvacawamaView Answer on Stackoverflow
Solution 5 - SwiftTotoroTotoroView Answer on Stackoverflow
Solution 6 - SwiftFredView Answer on Stackoverflow