我正在尝试实现一个扩展函数,该函数应该根据使用它的类的类型而有所不同。
这些对象必须是 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
您可以按如下方式实现,您只需公开aProtocol
to Objective-c
运行时间为overriding
其方法在extension
.
@objc protocol aProtocol {
typealias completionBlock = (_ finished:Bool)->()
func doSomething(completion: completionBlock)
}
extension UIView: aProtocol {
func doSomething(completion: (Bool) -> ()) {
print("Im an UIView")
}
}
extension UILabel {
override func doSomething(completion: (Bool) -> ()) {
// you can call super.doSomething(completion: completion)
print("im an UILabel")
}
}
extension UIImageView {
override func doSomething(completion: (Bool) -> ()) {
// you can call super.doSomething(completion: completion)
print("im an UIImageView")
}
}
Output:
Im an UIView
Im an UIView
im an UILabel
im an UIImageView
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)