String(Bool) is the easiest way.
var myBool = true
var boolAsString = String(myBool)
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>"}
let trueString = String(true) //"true"
let trueBool = Bool("true") //true
let falseBool = Bool("false") //false
let nilBool = Bool("foo") //nil
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>"
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.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With