gpt4 book ai didi

swift - Kotlin 中的条件接口(interface)

转载 作者:搜寻专家 更新时间:2023-10-31 08:16:05 25 4
gpt4 key购买 nike

在 Swift 中,我们可以根据条件定义一个可以被 classstruct 遵循的协议(protocol):

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)
}

}

AlertPresentable 协议(protocol)受到限制,只能由 UIViewController 遵守。有没有办法在 Kotlin 中实现相同的结果?

最佳答案

如果我正确理解您要完成的任务,您可以使用具有多种类型的扩展函数作为接收者类型的上限:

fun <T> T.presentAlert(message: String) 
where T : UIViewController, T : AlertPresentable {
// ...
}

关于swift - Kotlin 中的条件接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49235934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com