Swift 4: Printing out Bool optionals as either unwrapped true or false or as wrapped nil?

时间秒杀一切 提交于 2019-12-12 04:24:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!