Swift中能否为同时遵循两个协议的类型提供默认实现?
为同时遵循两个协议的类型添加默认实现
在Swift中,你可以通过带约束的协议扩展实现这个需求——给其中一个协议编写扩展,同时约束该类型必须同时遵循另一个协议。
修正并完成的代码示例
首先修正原协议的语法错误(属性声明需补充必要语法):
import UIKit protocol Coordinator { var navigationController: UINavigationController { get } } protocol Browsing { func openBrowser(url: String) }
接下来通过带约束的扩展,为同时遵循两个协议的类型添加openBrowser(url:)的默认实现:
extension Browsing where Self: Coordinator { func openBrowser(url: String) { // 这里编写你的业务逻辑,比如打开浏览器控制器 guard let url = URL(string: url) else { return } let browserVC = SFSafariViewController(url: url) navigationController.present(browserVC, animated: true) } }
使用示例
任何同时遵循Coordinator和Browsing的类,都会自动获得这个默认实现,无需手动编写:
class MainCoordinator: NSObject, Coordinator, Browsing { var navigationController: UINavigationController init(navigationController: UINavigationController) { self.navigationController = navigationController } // 无需手动实现openBrowser(url:),默认实现会自动生效 } // 调用示例 let nav = UINavigationController() let coordinator = MainCoordinator(navigationController: nav) coordinator.openBrowser(url: "https://example.com")
这种写法的核心是利用where Self: 协议的约束,让扩展的默认实现仅对同时满足两个协议的类型生效,完全适配你有多个类同时遵循这两个协议的场景。
内容的提问来源于stack exchange,提问作者Jalil
相关产品推荐
相关产品推荐

