Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HomeKit completion block in Swift: Cannot convert the expression's type 'Void' to type 'String!'

I'm playing with HomeKit, and I'm trying to add a new home. This is my code:

func addHome() {     homeManager.addHomeWithName("My House", completionHandler:         { (error: NSError!, home: HMHome!) in             if error             {                 NSLog("%@", error)             }         }) } 

This gives a compiler error:

Cannot convert the expression's type 'Void' to type 'String!' 

I've tried specifying a return type of Void:

... { (error: NSError!, home: HMHome!) -> Void in ... 

to no avail. Does anyone have any ideas how to fix this? Passing nil to the completion handler fixes the error, but of course I want to do something on completion.

like image 200
SmokeDetector Avatar asked Jun 22 '14 04:06

SmokeDetector


1 Answers

The parameters for your completionHandler closure are reversed, they should be:

(home: HMHome!, error: NSError!) 

Also note that you don't need to specify the types for the parameters, since the method signature specified them for you - thus you can simply list the parameter names you want to use, and they will automatically be assured to be of the correct type, for example:

homeManager.addHomeWithName("My House", completionHandler:{     home, error in     if error { NSLog("%@", error) }     }) 

--edit--

Also note that when I wrote 'you can simply list the parameter names you want to use, and they will automatically be assured to be of the correct type', that is to say that they will be typed according to the order in which they are listed - e.g. if you had used error, home in instead, then those would be your parameter names however the parameter error would be of type HMHome!, and home would be of type NSError! (since that is the order in which they appear in the parameter list for the closure in the method's signature)

like image 117
fqdn Avatar answered Sep 19 '22 15:09

fqdn