如何将Swift中的Bool转换为String?

63

假设有一个Bool?,我想要能够执行以下操作:

let a = BoolToString(optbool) ?? "<None>"

这将给我一个 "true""false""<None>"

BoolToString 是否有内置函数?


你希望真、假和<无>是字符串吗? - dannybess
@dannybess 抱歉,我错过了。是的。 - user1002430
6个回答

74

String(Bool) 是最简单的方式。

var myBool = true
var boolAsString = String(myBool)

60
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>"}

1
"none" 更改为 "<None>"。我想我们赢了! :-) - vacawama
这不是很正统的 Swift 编程,通过类型初始化器进行转换的约定是所有数据转换 API 的一个显著特征。然而,CustomStringConvertible 声明了 description,这是一个语义上应该用于调试目的而不是数据序列化的 API。你应该始终使用 String.init(_:) - Isaaс Weisberg
@IsaaсWeisberg 绝对是正确的。description 的文档不鼓励直接调用它。https://developer.apple.com/documentation/swift/customstringconvertible - Patrick

25
let trueString = String(true) //"true"
let trueBool = Bool("true")   //true
let falseBool = Bool("false") //false
let nilBool = Bool("foo")     //nil

2
这很完美。谢谢! - Baran Emre

7
您可以使用三目运算符?:
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>"

4
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.
    }

}


那么,不是吗?没有内置的方法吗? - user1002430
这里使用了CustomStringConvertible,即与已接受答案相同的解决方案。 - Isaaс Weisberg

0

你可以使用扩展来完成它!

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接