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

IosClosuresSwiftHomekit

Ios Problem Overview


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.

Ios Solutions


Solution 1 - Ios

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)

Solution 2 - Ios

Your arguments are ordered inconsistently; the signature for the completionHandler in addHomeWithName is

(HMHome!, NSError!) -> Void

thus use:

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

Using a trailing closure and allowing the compiler to infer the types lets you simplify the above to:

homeManager.addHomeWithName ("My House") {
  if $1 { NSLog ("%@", $1) }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSmokeDetectorView Question on Stackoverflow
Solution 1 - IosfqdnView Answer on Stackoverflow
Solution 2 - IosGoZonerView Answer on Stackoverflow