简体   繁体   中英

How to apply [weak self] to a swift function (not closure)

Say I have a network function that has a completion and I use it multiple times in my consumer like this:

class Network {
   func getNumber(completion: @escaping (Int) -> ()) {
      //some network code
      completion(5)
   }
}

class MyClass {
var num = 0
let network = Network()

func myFunc() {
    network.getNumber { [weak self] (number) in
        self?.num = number
    }
}

func myFunc2() {
    network.getNumber { [weak self] (number) in
        self?.num = number
    }
}

}

and to avoid duplicate code i replace the closures with a single function like this:

class MyClass {
var num = 0
let network = Network()

func myFunc() {
    network.getNumber(completion: self.handleData)
}

func myFunc2() {
    network.getNumber(completion: self.handleData)
}

func handleData(_ number: Int) -> () {
    self.num = number
}
}

The problem With this approach is that I am unable to capture self as weak in the handleData function.

The problem could be easily avoided by changing the handleData to be a closure like this:

lazy var handleData: (Int) -> () = { [weak self] in
    self?.num = $0
}

So my question is: is there a way to apply weak self for a function and not only a closure?

You could do this if you want to use weak reference to self on it's funcitons:

class MyClass {
    var num = 0

    func myFunc() {
        Network.getNumber { [weak self] in
            self?.handleData($0)
        }
    }

    func myFunc2() {
        Network.getNumber { [weak self] in
            self?.handleData($0)
        }
    }

    func handleData(_ number: Int) {
        self.num = number
    }
}

Also, you don't have to provide -> () for a function that returns nothing.

Taking into account that handleData can be really big, how about

func myFunc() {
    Network.getNumber { [weak self] i in self?.handleData(i) }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM