Code written Swift 2.0 on Xcode 7 beta
My question concerns passing functions are parameters. I have two functions: getImagesFromImgur and randomImageHandle. getImagesFromImgur is called at ViewDidLoad like this:
self.getImagesFromImgur(apiAction: "gallery.json",
handleResponse: self.randomImageHandle)
The getImagesFromImgur function looks like this:
func getImagesFromImgur(apiAction: String, handleResponse:
(NSData?, NSURLResponse?, NSError?) -> Void) {
...
let task = session.dataTaskWithRequest(request, completionHandler:
handleResponse)
...
}
The randomImgurHandle that is passed to getImagesFromImgur function in viewDidLoad looks like this:
func randomImageHandle(data: NSData?, response: NSURLResponse?,
error: NSError?) -> Void {
...
//code that edits the UI
...
}
So my question is, hqow can I pass self.randomImageHandle to self.getImagesFromImgur without specifying any argument values? I know dataTaskWithRequest passes the parameters to the handleResponse, and while I understand that, I'm confused on why the compiler doesn't force me to specify parameters.
EDIT: I'm passing a handle like this so I can have specific handles to match imgur's Api.
In Swift, functions are first-class types, and you can pass them around as variables. What you're actually doing is that getImagesFromImgur
is expecting a function that has the exact signature (NSData?, NSURLResponse?, NSError?) -> Void
(you don't need the Void here, BTW). The compiler checks for you that you passed in a method that has that signature, and thus you don't need to specify parameters.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.