MikeG
MikeG

Reputation: 4044

Is this the proper way to use callbacks in Swift?

While doing iOS development I have always used the delegate pattern to pass data between classes. Recently I have read that callbacks are often times a better option than delegation. I am just wondering if I am doing this properly. Below is my code

class ViewControlleer: UIViewController {

let NS = NetworkServices()
let someNum = 10

  func getData(){
        NS.mainFunc(someNum, callback: { (newNum) -> Void in
            let newNumber = newNum*50
            print(newNumber)
        })
    }
}

class NetworkServices {


  func mainFunc(num: Int, callback: (Int)-> Void){
      let newNum = num*3
      callback(newNum)
  }


}

Using this pattern throughout my code would be good practice? Is it correct to say - "The ViewController class knows about the NetworkServices class but the reverse is not true"- ?

Thanks

Upvotes: 2

Views: 291

Answers (1)

kofigumbs
kofigumbs

Reputation: 328

Yes, your theory is spot on! Callbacks a great way to start depending on abstractions (the type signature) instead of concretions (the class that will implement the functionality). Here are a couple of ways you could clean up your Swift notation though:

Trailing closures – Swift will infer your callback type from the parameter type, so the following is equivalent:

func getData(){
    NS.mainFunc(someNum) { newNum in
        let newNumber = newNum*50
        print(newNumber)
    }
}

Methods as functions – This form lets you name things more clearly:

func getData(){
    NS.mainFunc(someNum, callback: myPrint)
}

func myPrint(newNum: Int) {
    let newNumber = newNum*50
    print(newNumber)
}

Upvotes: 1

Related Questions