class Base: Equatable {
static func == (lhs: Base, rhs: Base) -> Bool {
lhs.id == rhs.id
}
let id: String
init(id: String) {
self.id = id
}
}
class SubClass: Base {
public var id2: String?
public init(id1: String, id2: String? = nil) {
self.id2 = id2
super.init(id: id1)
}
static func == (lhs: SubClass, rhs: SubClass) -> Bool {
lhs.id2 == rhs.id2 && lhs.id == rhs.id
}
}
print(a != b) // result: false
// Calls `Base` class's static func ==
print(a == b) // result: false
// Calls `SubClass` class's static func ==
我有一個簡單的超類和子類,子類繼承Base并實作
static func ==
呼叫時a != b,它呼叫Base的是類的==實作而不是SubClass' 的==實作,為什么?但是呼叫的時候a == b,其實是呼叫的SubClass實作==,為什么呢?
我期望!=和==呼叫SubClass的==實作
uj5u.com熱心網友回復:
這個問題早在 Swift 語言改進后就存在了(https://github.com/apple/swift-evolution/blob/master/proposals/0091-improving-operators-in-protocols.md)
并且作者也提到了這個問題。你可以檢查一下。https://github.com/apple/swift-evolution/blob/master/proposals/0091-improving-operators-in-protocols.md#class-types-and-inheritance
我找到的解決方案之一是定義一個isEqual函式。
class Superclass: Equatable {
var foo: Int
init(foo: Int) {
self.foo = foo
}
func isEqual(to instance: Superclass) -> Bool {
return self.foo == instance.foo
}
static func ==(lhs: Superclass, rhs: Superclass) -> Bool {
return type(of: lhs) == type(of: rhs) && lhs.isEqual(to: rhs)
}
}
class Subclass: Superclass {
var bar: String
init(foo: Int, bar: String) {
self.bar = bar
super.init(foo: foo)
}
override func isEqual(to instance: Superclass) -> Bool {
guard let instance = instance as? Subclass else {
return false
}
return self.foo == instance.foo && self.bar == instance.bar
}
}
let a = Subclass(foo: 1, bar: "a")
let b = Subclass(foo: 1, bar: "b")
print(a == b) // False
print(a != b) // True
參考:
- https://forums.swift.org/t/method-dispatching-issue-with-subclasses-implementing-equatable-protocol/4925
- https://forums.swift.org/t/implement-equatable-protocol-in-a-class-hierarchy/13844
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/496813.html
上一篇:Blazor組件類的繼承
