Using the Swift if let with logical AND operator &&

前端 未结 6 475
名媛妹妹
名媛妹妹 2021-01-30 19:13

We know that we can use an if let statement as a shorthand to check for an optional nil then unwrap.

However, I want to combine that with another expression

6条回答
  •  粉色の甜心
    2021-01-30 19:46

    It is not possible.

    From Swift grammar

    GRAMMAR OF AN IF STATEMENT

    if-statement → if ­if-condition­ code-block­ else-clause­opt­

    if-condition → expression­ | declaration­

    else-clause → else­ code-block­ | else­ if-statement­

    The value of any condition in an if statement must have a type that conforms to the BooleanType protocol. The condition can also be an optional binding declaration, as discussed in Optional Binding

    if-condition must be expression­ or declaration­. You can't have both expression and declaration.

    let foo = bar is a declaration, it doesn't evaluate to a value that conforms to BooleanType. It declares a constant/variable foo.

    Your original solution is good enough, it is much more readable then combining the conditions.

提交回复
热议问题