I am working through a tutorial on URLSession and URLRequest and ran into an interesting block of code... my first instinct was that this was a closure but I'm not 100% sure... if it is, I havent seen one like this until now. I've been familraiizng my self with closure since they are used a lot in networking code especially things like completion handlers...
Here is the code below... basically a URL is being constructed from a baseURLString decalred earlier and a relative path to a resource... Where I thought this was a closure was on line 39 where there is a pair of parantheses... Is this a closure syntaxt or some other special Swift syntax?
let url: URL = {
/**
* A string that contains the relative path. This path is relative to the base string. In other words, this string
* would be appended to the url made from the baseURLString to access a specific resource.
*
* For example, for the case .getPublicGists(), the relative path as described by GitHub is "gists/public". The resulting url
* would be a combination of the baseURLString and this relative path: "h ttps://api.github.com/gists/public".
*/
let relativePath: String?
switch self {
case .getPublicGists():
relativePath = "gists/public"
}
var url = URL(string: GistRouter2.baseURLString)!
if let relativePath = relativePath {
url = url.appendingPathComponent(relativePath)
}
return url
}()
This is a closure.
() is to ask execution of the closure
Get details here : h ttps://medium.com/@abhimuralidharan/functional-swift-all-about-closures-310bc8af31dd
let aClosure= { “hello, I’m a closure too.” }
let aString= { “hello, I’m a closure too.” }() // added () at the end.In the first statement, aClosure is actually a closure of type ()->String .
IN the second statement, we added () at the end .So it became a closure call. So, it executes the closure and returns a String . If it is not clear, refer the Inferred type closure section above.