Ben*_*min 4 interface kotlin swift swift-protocols
在Swift中,我们可以定义一个可以由a class
或struct
基于条件符合的协议:
protocol AlertPresentable {
func presentAlert(message: String)
}
extension AlertPresentable where Self : UIViewController {
func presentAlert(message: String) {
let alert = UIAlertController(title: “Alert”, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: “OK”, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
该AlertPresentable
协议受到限制,只能通过一致UIViewController
.有没有办法在Kotlin中获得相同的结果?
如果我正确理解了您要完成的任务,您可以使用多种类型的扩展函数作为接收器类型的上限:
fun <T> T.presentAlert(message: String)
where T : UIViewController, T : AlertPresentable {
// ...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
326 次 |
最近记录: |