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?
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?
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>"}
"none" to "<None>". I think we have a winner here! :-)CustomStringConvertible, which declares description is an API that semantically is supposed to be used not for data serialization but debugging purposes. You should always use String.init(_:) instead.description discourages calling it directly. developer.apple.com/documentation/swift/customstringconvertibleYou 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.
}
}
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>"