Search code examples
swiftoverridingextension-methodsswift5

Overriding a method in an extension, Swift


Since which version of Swift does the following code no longer build?

import Foundation

@objc class Class: NSObject {
  @objc func str() -> String {
    return "Hello, playground"
  }
}

class Subclass: Class {

}

extension Subclass {
  override func str() -> String {
    return "Hi"
  }
}

From my understanding, previous versions of Swift compiled this code with unexpected results. On Swift 5.1, it no longer builds.


Solution

  • Dynamic modifier

    You can do it using the dynamic modifier

    @objc class Animal: NSObject {
    
        @objc dynamic func saySomething() {
            print("I am an Animal")
        }
    
    }
    
    @objc class Dog: Animal { }
    
    extension Dog {
    
        override func saySomething() {
            print("I am a Dog")
        }
    
    }
    
    Dog().saySomething() // I am a Dog
    

    Tested with Swift 5.1.3