Ana Ana - 4 months ago 10
Swift Question

How to convert Swift Bool? -> String?

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
?

Answer
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>"}