简体   繁体   English

我可以在 Swift 中扩展 final 类吗?

[英]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.我正在为我使用 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.类/库的作者使用final关键字使其成为 final,可能是为了优化和防止覆盖其属性和方法。

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.扩展(如 Objective-C 类别)不允许存储属性。
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. Objective-C 中的一个常见(但 IMO hacky)解决方法是使用关联对象来获得类别内的存储。 This also works in Swift if you import ObjectiveC .如果您import ObjectiveC这也适用于 Swift。
This answer contains some details .这个答案包含一些细节

Yes, you can extend a final class.是的,您可以扩展 final 类。 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) 
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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