Optional type '$T11' cannot be used as a b

2020-03-21 05:40发布

问题:

Here is the code where I'm getting the error:

for (key, value) in info {
    let fieldValue: AnyObject? = value

    if (!fieldValue || fieldValue?.length == 0) { // this line gives the error
        informationComplete = false;
    } 
}

This is what XCode suggests I use which causes another error:

for (key, value) in info {
    let fieldValue: AnyObject? = value

    if ((!fieldValue || fieldValue?.length == 0) != nil) { //bool not convertible to string
        informationComplete = false;
    }
 }

Help is appreciated.

Thanks for your time

回答1:

Optionals are no longer considered boolean expression (as stated in the Swift Reference - Revision History):

Optionals no longer implicitly evaluate to true when they have a value and false when they do not, to avoid confusion when working with optional Bool values. Instead, make an explicit check against nil with the == or != operators to find out if an optional contains a value.

so you have to make it explicit as follows:

if (fieldValue == nil || ...

I remember that changed in beta 6 - were you using beta 5?