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
请注意,这是提供抽象的克拉ss就像结构一样,但是类也可以实现相同的协议。
Notice that this is providing "abstract class" like features even for structs, but classes can also implement the same protocol.
还要注意,实现Employee协议的每个类或结构都必须声明annualSalary属性再次。
Also notice that every class or struct that implements the Employee protocol will have to declare the annualSalary property again.
最重要的是,请注意没有动态调度。当在存储为 SoftwareEngineer
的实例上调用 logSalary
时,它会调用该方法的重写版本。在将实例调用 Employee
后,在实例上调用 logSalary
时,它会调用原始实现(它不会即使实例实际上是软件工程师
,也不会动态调度到被覆盖的版本。
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屋!