Search code examples
swiftreturnclosuresimplicitcompletion-block

How to Supress implicit return from a closure with Void return type in Swift


lets consider we have a closure like: (used as completionHandler)

func doSomething (completionHandler : (done : Bool)->Void )->Void {
      ...
     completionHandler(true)
}

now if we want to do something like that :

doSomething({ (done : Bool)-> Void
  var data : NSDictionary = NSDictionary()
  data.setValue("data1", forKey: "data1")   // 1
  data.setValue("data2", forKey: "data2")   // 2
  data.setValue("data3", forKey: "data3")   // 3
})

it returns on line // 1 and ignores the remaining lines because the returning type of setValue of NSDictionary is Void. My Question is, is there a way to suppress this behaviour?


Solution

  • I recreated your example with your code (with minor tweaks) and didn't have the problem you described. I used a swift dictionary instead though, since I have no knowledge about Obj-C.

    func doSomething(completionHandler: Bool -> Void) {
        completionHandler(true)
    }
    
    doSomething() { finished in
        var data = [String: String]()
        data.updateValue("data1", forKey: "data1")  // 1
        data.updateValue("data2", forKey: "data2")  // 2
        data.updateValue("data3", forKey: "data3")  // 3
    
        for (key, value) in data {
            println("Key: \(key) & Value: \(value)")
        }
    }
    

    The output is:

    Key: data2 & Value: data2
    Key: data1 & Value: data1  // Not sure why data1 is second here
    Key: data3 & Value: data3
    

    I doubt using NSDictionary could be the cause of it, maybe something else is causing it to return?