How to use trailing closure in if condition?

后端 未结 2 1681
感情败类
感情败类 2020-12-19 21:43

Here is the code:

class Person {
}

func lastNameForPerson(person: Person, caseFolding: ((String)->(String))? = nil) -> String {
    if let folder = ca         


        
相关标签:
2条回答
  • 2020-12-19 21:50

    Put your function call between parentheses:

    if "SMITH" == (lastNameForPerson(Person()) {$0.uppercaseString}) {
    

    otherwise the == operator takes precedence and the compiler evaluates it as

    if ("SMITH" == lastNameForPerson(Person())) {$0.uppercaseString} {
    

    which is not valid code.

    0 讨论(0)
  • 2020-12-19 22:11

    You have to put parentheses around the function call:

    if "SMITH" == (lastNameForPerson(Person()) {$0.uppercaseString}) {
        print("It's bob")
    }
    

    Or you put them around the == comparison (around the if condition) in a C-style manner:

    if ("SMITH" == lastNameForPerson(Person()) {$0.uppercaseString}) {
        print("It's bob")
    }
    

    Alternatively, you can move the closure inside the parameter list (though this requires you to explicitly name the parameter):

    if "SMITH" == lastNameForPerson(Person(), caseFolding: {$0.uppercaseString}) {
        print("It's bob")
    }
    

    The reason this problem arises is that the if statement 'claims' the {} block, i.e. it doesn't belong to the lastNameForPerson call any more. For the compiler, the second code block now looks like a normal block that wasn't properly separated from the previous (if) statement.


    You should probably consider avoiding a construct like this in general, since it might be hard to read (at first). Instead, you could store the result of the function call in a variable and compare that instead:

    let lastName = lastNameForPerson(Person()) {$0.uppercaseString}
    if "SMITH" == lastName {
        print("It's bob")
    }
    
    0 讨论(0)
提交回复
热议问题