Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

swift - How to use trailing closure in if condition?

Here is the code:

class Person {
}

func lastNameForPerson(person: Person, caseFolding: ((String)->(String))? = nil) -> String {
    if let folder = caseFolding {
        return folder("Smith")
    }
    return "Smith"
}

print(lastNameForPerson(Person())) // Prints "Smith"
print(lastNameForPerson(Person()) {$0.uppercaseString}) // Prints "SMITH"

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

Was expecting to get "It's bob". But instead got the error:

Consecutive statements must be separated by a new line

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...