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
685 views
in Technique[技术] by (71.8m points)

swift - Parameters after opening bracket

I am doing my first steps in Vapor, the web framework for Swift.

The first piece of code that called my attention was this:

app.get("welcome") { request in 
    return "Hello"
}

I don't understand the syntax here. I mean, I'm calling app.get() method, but I'm also defining some kind of function where request is a parameter. I know that this will result in a get method accessible by a /welcome URL and will return "Hello". What is not clear for me is how this piece of code works and how the compiler interprets it.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This is called trailing closure syntax.

I give a nice rundown of the various syntactic sugars of closures in this answer.

The expanded version of this code would be:

app.get("welcome", { (request: Request) throws -> ResponseRepresentable in 
    return "Hello"
})

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

...