Native Optional Methods in Swift Protocols

There are a LOT of prior suggestions similar to this:

In particular, this was the SE to get rid of optional requirements in Swift (it was once a thing, very very very early on). However, I can't find the rationale behind not wanting "optional requirements" (funny name) in Swift Protocols - I only see it being stated. The SE forums thread was also rather sparse, so I'm not sure if I'm missing something.

=====

I'm personally in favour of optional methods. I have a lot of delegate-style protocols in my apps, which usually look like:

protocol CatDelegate {
    func catDidSit(_ cat: Cat)
    func catDidStand(_ cat: Cat)
    func catDidEat(_ cat: Cat)
}

protocol CatDelegate {
    /* default implementations, it's just {} for each case */
}

class CatFoodTracker: CatDelegate {
    func catDidEat(_ cat: Cat) {
        print("CAT ATE FOOD")
    }
}

However, the default implementations are a bit of a pain when I need to refer to the original functions in docc (since they have the same name and signature), and honestly just having those functions be optional would be fine. We can just

  • Bring back the optional keyword
  • Call functions using objectConformingToProtocol.myMethod?() (we use this syntax already for objc optional methods and optional closures)
  • Remove a default implementation by func myMethod?() = nil or smth like that
5 Likes