-1

what approach does Apple use in Swift instead of override, how can I write this without using the @objc marker

import Foundation

class A {
    init() {}
}
extension A {
    @objc func foo() {
        print("foo")
    }
}

class B: A {
    override func foo() {
        print("yes2")
    }
}

A().foo()
B().foo()

maybe protocols? but how?

EvGeniy Ilyin
  • 1,817
  • 1
  • 21
  • 38
  • This is not possible in pure Swift by design. Also duplicate of https://stackoverflow.com/a/38274660 – Kamil.S Nov 11 '19 at 13:24
  • Your question is unclear. You don't need either `override` or `@objc` for `extension` methods. – user28434'mstep Nov 11 '19 at 13:24
  • The Swift language does not support overriding methods in extensions (unless with the @objc, but that is a kludge). You could possibly achieve what you wanted by taking a compositional approach; using a protocol to define the method, a default implementation in a protocol extension as the "standard" method, and then implementing local method in those classes that needed something different. How practical this is would depend on what you're looking to achieve. – flanker Nov 11 '19 at 13:32

1 Answers1

1

You can define a protocol and provide a default method implementation. Then all you need is to comform to that protocol and provide its own foo method if necessary:

protocol Fooable {
    func foo()
}

extension Fooable {
    func foo() {
        print("default implementation")
    }
}

class A: Fooable { }

class B: A {
    func foo() {
        print("B implementationn")
    }
}

let a = A()
let b = B()

a.foo()
b.foo() 

This will print

default implementation

B implementationn

Community
  • 1
  • 1
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571