Swift 编译器说的关于 Bool("") 的奇怪消息是什么意思?

What are the strange messages Swift compiler say about Bool("") means?

来自 python 并用空字符串作为 if 语句的条件测试 Swift。

  1. 错误信息是什么意思?
    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'
  2. 这种行为有什么用?
    Bool("") return nil
    这么设计的目的是什么?

实际上不是 3 条错误消息。这是 1 条错误消息,外加 2 条建议的解决方法。

if 语句中的条件应为 Bool,但此处的表达式 Bool("") 属于 Bool? 类型。编译器看到这只是一个包裹在可选中的 Bool,所以它建议解包可选的方法,以便获得 if 语句期望的类型 - Bool.

第一个建议的方法是在 Bool("")nil 时使用 ?? 运算符] 提供默认值,如下所示:

if Bool("") ?? true {}

第二种方法是强制解包,如果 Bool("")nil:

,基本上会导致程序崩溃
if Bool("")! {}

虽然在这种情况下,这两种修复方法都非常愚蠢,因为 Bool("") 始终为零。但重点是,当您需要解包可选时,编译器会建议这两种方式。

继续你的第二个问题,为什么 Bool.init return 是可选的?

初始化器可能 return nil 因为它们可能 失败 ,这些初始化器称为 failable initialisers。使用 String 初始化 Bool 可能会失败,因为只有字符串 "true" 和 "false" 才能成功创建 Bool。所有其他字符串不代表 Bool 值。