Search code examples
swiftcompiler-errorsinitialization

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


Come from python and test Swift with empty string as condition of if statement.

  1. What's the error messages mean ?
    if Bool("") {} gives three compiler messages

    • 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. What's the use of this behavior?
    Bool("") return nil
    what's the purpose to design it like this?


Solution

  • It's not actually 3 error messages. It's 1 error message, plus 2 suggested ways to solve it.

    The condition in an if statement should be a Bool, but the expression you have here, Bool("") is of type Bool?. The compiler sees that this is just a Bool wrapped in an optional, so it suggests ways to unwrap the optional, so as to get the type expected by the if statement - Bool.

    The first suggested way is to provide a default value for when Bool("") is nil using the ?? operator]1, like this:

    if Bool("") ?? true {}
    

    The second way is to force unwrap it, essentially crashing the program if Bool("") is nil:

    if Bool("")! {}
    

    Though in this case both of these ways of fixing it is quite silly, because Bool("") is always nil. But the point is, these are the two ways the compiler will suggest, when you need to unwrap an optional.

    Moving on to your second question, why does Bool.init return an optional?

    Initialisers may return nil because they may fail, and these initialisers are called failable initialisers. Initialising a Bool with a String may fail because only the strings "true" and "false" will successfully create Bools. All other strings do not represent Bool values.