Swi*_*ing 1 private class subclass superclass swift
所以我有以下超类:
class Vehicle {
private var _maxSpeed: Int = 100
var maxSpeed: Int {
get {
return _maxSpeed
}
var tooFast: Bool {
get {
if maxSpeed >= 140 {
return false
} else {
return true
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
另外,我有一些子类,我想覆盖maxSpeed ...每个例子:
class SuperCar: Vehicle {
//override the maxspeed...
}
Run Code Online (Sandbox Code Playgroud)
但是我应该怎么做呢?或者,如果我们不将其设为私有,这是否可行?我试图将私有部分扔出窗外,但这不会起作用......
class Vehicle {
var maxSpeed: Int = 100
var tooFast: Bool {
get {
if maxSpeed >= 140 {
return false
} else {
return true
}
}
}
}
class SuperCar: Vehicle {
// override the maxSpeed...
override var maxSpeed: Int = 200
// Will not work...
}
Run Code Online (Sandbox Code Playgroud)
只需将类和子类放在同一个文件中即可.private与继承无关.它与文件范围有关.同一文件中的任何内容都可以访问private成员.
也就是说,你几乎肯定不应该在这里使用继承.Vehicle应该几乎肯定是一个协议.那么你就不会有任何继承或头痛private.
protocol Vehicle {
var maxSpeed: Int {get}
}
extension Vehicle {
// Default implementation if none is given
var maxSpeed: Int { return 100 }
// Another method that applies to all Vehicles
var tooFast: Bool {
return maxSpeed < 140 // (feels like this should be >= 140, but matching your code)
}
}
struct SuperCar: Vehicle {
// override the default implementation for the protcocol
var maxSpeed = 200
}
Run Code Online (Sandbox Code Playgroud)