Swift不允许您覆盖变量。stored property
除此之外,您可以使用computed property
class A {
var property1 = "A: Stored Property 1"
var property2: String {
get {
return "A: Computed Property 2"
}
}
let property3 = "A: Constant Stored Property 3"
//let can not be a computed property
func foo() -> String {
return "A: foo()"
}
}
class B: A {
//now it is a computed property
override var property1: String {
set { }
get {
return "B: overrode Stored Property 1"
}
}
override var property2: String {
get {
return "B: overrode Computed Property 2"
}
}
override func foo() -> String {
return "B: foo()"
}
//let can not be overrode
}
func testPoly() {
let a = A()
XCTAssertEqual("A: Stored Property 1", a.property1)
XCTAssertEqual("A: Computed Property 2", a.property2)
XCTAssertEqual("A: foo()", a.foo())
let b = B()
XCTAssertEqual("B: overrode Stored Property 1", b.property1)
XCTAssertEqual("B: overrode Computed Property 2", b.property2)
XCTAssertEqual("B: foo()", b.foo())
//B cast to A
XCTAssertEqual("B: overrode Stored Property 1", (b as! A).property1)
XCTAssertEqual("B: overrode Computed Property 2", (b as! A).property2)
XCTAssertEqual("B: foo()", (b as! A).foo())
}
与Java相比,它更加清楚,因为在编译时定义了类字段(有效运行),所以类字段不能被覆盖并且不支持多态。它称为变量隐藏[关于]不建议使用此技术,因为它很难阅读/支持
[迅捷属性]