【发布时间】:2019-08-05 11:38:53
【问题描述】:
我正在尝试实现一个扩展函数,该函数应该根据使用它的类的类型而有所不同。 对象需要是 UIView(或子类)。它应该始终使用在指定类型上扩展的函数,但如果它不符合其中任何一个,则应该使用 UIView 方法(作为后备)。
这是我正在尝试做的一个示例:
protocol aProtocol {
typealias completionBlock = (_ finished:Bool)->()
func doSomething(completion: completionBlock)
}
extension UIView: aProtocol {
func doSomething(completion: (Bool) -> ()) {
print("Im an UIView")
}
}
extension aProtocol where Self: UILabel {
func doSomething(completion: (Bool) -> ()) {
print("im an UILabel")
}
}
extension aProtocol where Self: UIImageView {
func doSomething(completion: (Bool) -> ()) {
print("im an UIImageView")
}
}
执行:
UIView().doSomething { (foo) in } // Should print "Im an UIView"
UIButton().doSomething { (foo) in } // Should print "Im an UIView" (UIButton doesent have specified extended function so should fall back on the UIView function)
UILabel().doSomething { (foo) in } // Should print "im an UILabel"
UIImageView().doSomething { (foo) in } // Should print "im an UIImageView"
现在打印:
Im an UIView
Im an UIView
Im an UIView
Im an UIView
这意味着它总是使用 UIView 方法,即使我希望它使用它自己的方法。我的目标是这样打印:
Im an UIView
Im an UIView
im an UILabel
im an UIImageView
【问题讨论】:
-
因为一个UILabel永远是一个UIView,
-
@vollan 当然,UILabel 永远是 UIView 的子类。我想弄清楚的是子类的指定函数是否可以覆盖 UIView 函数。
-
抱歉,误会了。在下面发布答案。
-
@Pointblaster 查看我的答案。我解释了为什么会发生这种情况以及如何满足您的需求。
-
问题是扩展没有创建覆盖。他们定义了一种新方法。
标签: ios swift uiview protocols