来自python并使用空字符串测试Swift作为if语句的条件。
if Bool("") {}
给出三个编译器消息error: value of optional type 'Bool?' must be unwrapped to a value of type 'Bool'
note: coalesce using '??' to provide a default when the optional value contains 'nil'
note: force-unwrap using '!' to abort execution if the optional value contains 'nil'
Bool("")
返回nil
这样设计的目的是什么? 最佳答案
这实际上不是3条错误消息。这是1条错误消息,外加2条建议的解决方法。if
语句中的条件应该是Bool
,但是您在此处使用的表达式Bool("")
的类型为Bool?
。编译器看到这只是包裹在可选变量中的Bool
,因此它建议了解开可选变量的方法,以便获得if
语句期望的类型-Bool
。
第一种建议的方法是使用Bool("")
运算符1为nil
是??
时提供默认值,如下所示:
if Bool("") ?? true {}
第二种方法是强制打开它,如果
Bool("")
是nil
,则实质上使程序崩溃:if Bool("")! {}
尽管在这种情况下,这两种固定方法都非常愚蠢,因为
Bool("")
始终为nil。但是关键是,当您需要拆开 optional 时,这是编译器建议的两种方式。继续讲第二个问题,为什么
Bool.init
返回一个可选的?初始化程序可能因为失败而返回
nil
,这些初始化程序称为failable initialisers。用Bool
初始化String
可能会失败,因为只有字符串“true”和“false”才能成功创建Bool
。所有其他字符串都不代表Bool
值。
关于swift - Swift编译器对Bool (“”)意味着什么奇怪的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56078751/