问题
Basically I want to print the below value as either "true", "false" or "nil". If I try just using the wrapped value I get the "nil" I want but gain the unwanted "Optional(true)" or "Optional(false). If I force unwrap the value and the value is nil I get a fatal error. I tried the below code as I've seen it work for Strings but because "nil" is not of type Bool it's not accepted. Any solutions to this?
var isReal: Bool?
String("Value is \(isReal ?? "nil")")
I'm exporting to a csv file and it's useful to know if this value is true or false or hasn't been checked yet.
回答1:
If you want a one-liner:
var isReal: Bool?
let s = "Value is \(isReal.map { String($0) } ?? "nil")"
print(s) // "Value is nil"
Or with a custom extension:
extension Optional {
var descriptionOrNil: String {
return self.map { "\($0)" } ?? "nil"
}
}
you can do
var isReal: Bool?
let s = "Value is \(isReal.descriptionOrNil)"
print(s) // "Value is nil"
and this works with all optional types.
回答2:
Just do an optional binding and make this:
if let value = isReal {
print(value) // will either be true or false
} else {
// isReal is nil
}
回答3:
Although I would suggest to implement it using Optional binding as what mentioned in Rashwan L's answer, if you are aiming -for some reason- to declare it as one lined string, you could simply do it like this:
var isReal: Bool?
let myString = isReal != nil ? "Value is \(isReal!)" : "Value is nil"
来源:https://stackoverflow.com/questions/46933285/swift-4-printing-out-bool-optionals-as-either-unwrapped-true-or-false-or-as-wra