Can I extend a final class in Swift?

6.5k views Asked by At

I'm using a third-party library for a new app that I'm making using Swift. The author of the class/library has made it final using the final keyword, probably to optimise and to prevent overriding its properties and methods.

Example:

final public class ExampleClass {
   // Properties and Methods here
}

Is it possible for me extend the class and add some new properties and methods to it without overriding the defaults?

Like so:

extension ExampleClass {
    // New Properties and Methods inside
}
4

There are 4 answers

0
ScottyBlades On

While you cannot create new stored properties in extensions you can add methods and computed properties.

Example computed property:

extension ExampleClass { 

  // computed properties do not have a setter, only get access
  var asInt: Int? { 
    Int(aStringPropertyOnTheClass) 
  }
}
0
LoVo On

An extension may not contain stored properties but you can add methods inside.

1
Thomas Zoechling On

Extensions (like Objective-C categories) don't allow stored properties.
Methods and computed properties are fine though.

A common (but IMO hacky) workaround in Objective-C was to use associated objects to gain storage within categories. This also works in Swift if you import ObjectiveC.
This answer contains some details.

0
David Reich On

Yes, you can extend a final class. That extension has to follow the usual rules for extensions, otherwise it's nothing special.