12

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
}
Cœur
  • 34,719
  • 24
  • 185
  • 251
metpb
  • 493
  • 8
  • 20

4 Answers4

7

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

LoVo
  • 1,571
  • 15
  • 20
5

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.

Community
  • 1
  • 1
Thomas Zoechling
  • 33,778
  • 3
  • 80
  • 111
3

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

matt
  • 485,702
  • 82
  • 818
  • 1,064
David Reich
  • 669
  • 6
  • 12
-1

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) 
  }
}
ScottyBlades
  • 9,795
  • 4
  • 62
  • 71