Can I extend a final class in Swift?
Asked Answered
W

4

14

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
}
Willodeanwilloughby answered 5/11, 2015 at 8:21 Comment(0)
L
7

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

Lp answered 5/11, 2015 at 8:24 Comment(0)
A
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.

Alula answered 5/11, 2015 at 8:36 Comment(1)
Let's remind that it only works for associating NSObject subclasses.Superclass
F
4

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

Flamenco answered 24/7, 2019 at 1:41 Comment(0)
L
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) 
  }
}
Lodged answered 30/7, 2020 at 6:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.