简体   繁体   中英

Can I extend a final class in Swift?

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
}

扩展可能不包含存储的属性,但您可以在其中添加方法。

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 .

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

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) 
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM