使用 Swift 协议和扩展覆盖对象方法
Override object method using Swift protocols and extensions
我想覆盖在框架中声明并在扩展中实现的方法。
这是我试过的方法:
import UIKit
// Code from a dependency
class Object { // UIViewController
func printSomething() {
print("something")
}
}
// My code
protocol SayHelloProtocol {
func hello()
func name() -> String
}
extension SayHelloProtocol {
func hello() {
print("Hello " + name())
}
func name() -> String {
"someone"
}
}
class MyHelloObject: Object, SayHelloProtocol {
override func printSomething() {
hello()
}
}
class MyHelloChildObject: MyHelloObject {
func name() -> String {
"You"
}
}
MyHelloObject().printSomething()
MyHelloChildObject().printSomething()
这将打印:
Hello someone
Hello someone
但我想重写该方法以便打印:
Hello someone
Hello You
是否可以覆盖在扩展中实现的方法?
如果您将 name()
函数也添加到 MyHelloObject
:
,它会起作用
class MyHelloObject: Object, SayHelloProtocol {
override func printSomething() {
hello()
}
func name() -> String {
"Someone"
}
}
class MyHelloChildObject: MyHelloObject {
override func name() -> String {
"You"
}
}
我想覆盖在框架中声明并在扩展中实现的方法。
这是我试过的方法:
import UIKit
// Code from a dependency
class Object { // UIViewController
func printSomething() {
print("something")
}
}
// My code
protocol SayHelloProtocol {
func hello()
func name() -> String
}
extension SayHelloProtocol {
func hello() {
print("Hello " + name())
}
func name() -> String {
"someone"
}
}
class MyHelloObject: Object, SayHelloProtocol {
override func printSomething() {
hello()
}
}
class MyHelloChildObject: MyHelloObject {
func name() -> String {
"You"
}
}
MyHelloObject().printSomething()
MyHelloChildObject().printSomething()
这将打印:
Hello someone
Hello someone
但我想重写该方法以便打印:
Hello someone
Hello You
是否可以覆盖在扩展中实现的方法?
如果您将 name()
函数也添加到 MyHelloObject
:
class MyHelloObject: Object, SayHelloProtocol {
override func printSomething() {
hello()
}
func name() -> String {
"Someone"
}
}
class MyHelloChildObject: MyHelloObject {
override func name() -> String {
"You"
}
}