How to convert Swift Bool? -> String? How to convert Swift Bool? -> String? swift swift

How to convert Swift Bool? -> String?


String(Bool) is the easiest way.

var myBool = truevar boolAsString = String(myBool)


let b1: Bool? = truelet b2: Bool? = falselet b3: Bool? = nilprint(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>"}


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