13

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
  • 37,241
  • 25
  • 195
  • 267
metpb
  • 513
  • 8
  • 20

4 Answers4

7

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

LoVo
  • 1,856
  • 19
  • 21
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
  • 34,177
  • 3
  • 81
  • 112
4

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

matt
  • 515,959
  • 87
  • 875
  • 1,141
David Reich
  • 709
  • 6
  • 14
0

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
  • 12,189
  • 5
  • 77
  • 85