Swift:从自定义实现中调用协议 func 的默认实现
Swift: calling default implementation of protocol func from custom implementation
我认为标题和示例已经说明了一切:) 这有可能吗?
protocol Foo {
func bar()
}
extension Foo {
func bar() {
print("bar form extension")
}
}
enum Day: Foo {
case sunday, monday
func bar() {
switch self {
case .sunday: print("bar custom implementation")
case .monday: // I want to call the default implementation
}
}
}
简单地从协议中删除声明,只有扩展定义。然后,如果具体类型没有重写或者如果它除了符合 Foo
之外对具体类型一无所知,编译器将仅使用扩展方法
protocol Foo {
// Declaration was deleted
}
extension Foo {
func bar() {
print("bar form extension")
}
}
enum Day: Foo {
case sunday, monday
func bar() {
switch self {
case .sunday: print("bar custom implementation")
case .monday: (self as Foo).bar()
}
}
}
Day.sunday.bar() // prints "bar custom implementation"
Day.monday.bar() // prints "bar form extension"
您需要 (self as Foo)
让编译器忘记 self
是一个 Day
并返回到 Foo
扩展函数。
我认为标题和示例已经说明了一切:) 这有可能吗?
protocol Foo {
func bar()
}
extension Foo {
func bar() {
print("bar form extension")
}
}
enum Day: Foo {
case sunday, monday
func bar() {
switch self {
case .sunday: print("bar custom implementation")
case .monday: // I want to call the default implementation
}
}
}
简单地从协议中删除声明,只有扩展定义。然后,如果具体类型没有重写或者如果它除了符合 Foo
protocol Foo {
// Declaration was deleted
}
extension Foo {
func bar() {
print("bar form extension")
}
}
enum Day: Foo {
case sunday, monday
func bar() {
switch self {
case .sunday: print("bar custom implementation")
case .monday: (self as Foo).bar()
}
}
}
Day.sunday.bar() // prints "bar custom implementation"
Day.monday.bar() // prints "bar form extension"
您需要 (self as Foo)
让编译器忘记 self
是一个 Day
并返回到 Foo
扩展函数。