假设有一个Bool?
,我想要能够执行以下操作:
let a = BoolToString(optbool) ?? "<None>"
这将给我一个 "true"
、"false"
或 "<None>"
。
BoolToString
是否有内置函数?
String(Bool) 是最简单的方式。
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"
或者您可以将“一句话”定义为一个函数,它适用于 Bool 和 Bool? 两种情况。
func BoolToString(b: Bool?)->String { return b?.description ?? "<None>"}
"none"
更改为 "<None>"
。我想我们赢了! :-) - vacawamaCustomStringConvertible
声明了 description
,这是一个语义上应该用于调试目的而不是数据序列化的 API。你应该始终使用 String.init(_:)
。 - Isaaс Weisbergdescription
的文档不鼓励直接调用它。https://developer.apple.com/documentation/swift/customstringconvertible - Patricklet trueString = String(true) //"true"
let trueBool = Bool("true") //true
let falseBool = Bool("false") //false
let nilBool = Bool("foo") //nil
?:
:let a = optBool == nil ? "<None>" : "\(optBool!)"
或者你可以使用 map
:
let a = optBool.map { "\($0)" } ?? "<None>"
optBool.map { "\($0)" }
正是你想要 BoolToString
实现的功能;它返回一个 String?
,可以是 Optional(true)
、Optional(false)
或者 nil
。然后使用 nil 合并运算符 ??
来展开该值或用 "<None>"
替换 nil
。
更新:
这也可以写成:let a = optBool.map(String.init) ?? "<None>"
或者:
let a = optBool.map { String($0) } ?? "<None>"
var boolValue: Bool? = nil
var stringValue = "\(boolValue)" // can be either "true", "false", or "nil"
或者更为冗长的自定义函数:
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.
}
}
你可以使用扩展来完成它!
extension Optional where Wrapped == Bool {
func toString(_ nilString: String = "nil") -> String {
self.map { String($0) } ?? nilString
}
}
使用方法:
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>"