Swift 4:以非包装的true或false或包装为nil的形式输出Bool可选件吗? [英] Swift 4: Printing out Bool optionals as either unwrapped true or false or as wrapped nil?

查看:160
本文介绍了Swift 4:以非包装的true或false或包装为nil的形式输出Bool可选件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想将以下值打印为"true","false"或"nil".如果我尝试仅使用包装的值,则会得到我想要的"nil",但会得到不需要的"Optional(true)"或"Optional(false).如果我强制拆开该值,而该值为nil,则会出现致命错误.我尝试了下面的代码,因为我发现它适用于Strings,但是因为"nil"不是Bool类型,所以不被接受.对此有任何解决方案吗?

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")")

我正在导出到一个csv文件,知道此值是true还是false或尚未检查该值很有用.

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.

推荐答案

如果您想要单线:

var isReal: Bool?
let s = "Value is \(isReal.map { String($0) } ?? "nil")"
print(s) // "Value is nil"

或带有自定义扩展名:

extension Optional {
    var descriptionOrNil: String {
        return self.map { "\($0)" } ?? "nil"
    }
}

你可以做

var isReal: Bool?
let s = "Value is \(isReal.descriptionOrNil)"
print(s) // "Value is nil"

,这适用于所有可选类型.

and this works with all optional types.

这篇关于Swift 4:以非包装的true或false或包装为nil的形式输出Bool可选件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆