Swift 语言中的抽象类 [英] Abstract classes in Swift Language
问题描述
有没有办法在 Swift 语言中创建一个抽象类,或者这是像 Objective-C 一样的限制?我想创建一个抽象类,类似于 Java 定义的抽象类.
Is there a way to create an abstract class in the Swift Language, or is this a limitation just like Objective-C? I'd like to create a abstract class comparable to what Java defines as an abstract class.
推荐答案
Swift 中没有抽象类(就像 Objective-C 一样).您最好的选择是使用 协议,类似于 Java 接口.
There are no abstract classes in Swift (just like Objective-C). Your best bet is going to be to use a Protocol, which is like a Java Interface.
在 Swift 2.0 中,您可以使用协议扩展添加方法实现和计算属性实现.您唯一的限制是不能提供成员变量或常量,并且没有动态调度.
With Swift 2.0, you can then add method implementations and calculated property implementations using protocol extensions. Your only restrictions are that you can't provide member variables or constants and there is no dynamic dispatch.
这种技术的一个例子是:
An example of this technique would be:
protocol Employee {
var annualSalary: Int {get}
}
extension Employee {
var biweeklySalary: Int {
return self.annualSalary / 26
}
func logSalary() {
print("$(self.annualSalary) per year or $(self.biweeklySalary) biweekly")
}
}
struct SoftwareEngineer: Employee {
var annualSalary: Int
func logSalary() {
print("overridden")
}
}
let sarah = SoftwareEngineer(annualSalary: 100000)
sarah.logSalary() // prints: overridden
(sarah as Employee).logSalary() // prints: $100000 per year or $3846 biweekly
请注意,这甚至为结构提供了类似抽象类"的功能,但类也可以实现相同的协议.
Notice that this is providing "abstract class" like features even for structs, but classes can also implement the same protocol.
另请注意,每个实现 Employee 协议的类或结构都必须再次声明 yearSalary 属性.
Also notice that every class or struct that implements the Employee protocol will have to declare the annualSalary property again.
最重要的是,请注意没有动态调度.当在存储为 SoftwareEngineer
的实例上调用 logSalary
时,它会调用该方法的覆盖版本.当 logSalary
在实例被转换为 Employee
后被调用时,它调用原始实现(它不会动态分派到覆盖的版本,即使实例实际上是一个软件工程师
.
Most importantly, notice that there is no dynamic dispatch. When logSalary
is called on the instance that is stored as a SoftwareEngineer
it calls the overridden version of the method. When logSalary
is called on the instance after it has been cast to an Employee
, it calls the original implementation (it doesn't not dynamically dispatch to the overridden version even though the instance is actually a Software Engineer
.
有关更多信息,请查看有关该功能的精彩 WWDC 视频:构建更好的应用Swift 中的值类型
For more information, check great WWDC video about that feature: Building Better Apps with Value Types in Swift
这篇关于Swift 语言中的抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!