Tag: 协议扩展

从协议扩展调用select器

我正在构build简单的主题引擎,并希望有一个扩展,它将UISwipeGestureRecognizer添加到UIViewController 这是我的代码: protocol Themeable { func themeDidUpdate(currentTheme: Theme) -> Void } extension Themeable where Self: UIViewController { func switchCurrentTheme() { Theme.switchTheme() themeDidUpdate(Theme.currentTheme) } func addSwitchThemeGestureRecognizer() { let gestureRecognizer = UISwipeGestureRecognizer(target: self, action:#selector(Self.switchCurrentTheme)) gestureRecognizer.direction = .Down gestureRecognizer.numberOfTouchesRequired = 2 self.view.addGestureRecognizer(gestureRecognizer) } } 当然编译器不能find#selector(Self.switchCurrentTheme)因为它没有通过@objc指令公开。 是否有可能将此行为添加到我的扩展? 更新: Theme是一个Swift枚举,所以我不能在Themeable协议前添加@objc

Swift协议扩展方法分派与超类和子类

我发现了一个有趣的行为,这似乎是一个错误… 根据以下文章描述的行为: https://medium.com/ios-os-x-development/swift-protocol-extension-method-dispatch-6a6bf270ba94 http://nomothetis.svbtle.com/the-ghost-of-swift-bugs-future 输出不是我所期望的,当我添加SomeSuperclass ,而不是直接采用协议。 protocol TheProtocol { func method1() } extension TheProtocol { func method1() { print("Called method1 from protocol extension") } func method2NotInProtocol() { print("Called method2NotInProtocol from protocol extension") } } // This is the difference – adding a superclass class SomeSuperclass: TheProtocol { } // It works as expected when it […]