美文网首页
protocol extension中where用法

protocol extension中where用法

作者: pigLily | 来源:发表于2021-12-09 10:38 被阅读0次

在Swift2.0中,引入了protocol extension。在有些时候,我们会希望一个协议扩展的默认实现只在某些特定的条件下适用,这时我们就可以用where关键字来进行限定。标准库中的协议扩展大量使用了这个技术来进行限定,比如Sequence的sorted方法就被定义在这样一个类型限制的协议扩展中。

protocol ToastViewProtocol {}

extension ToastViewProtocol where Self: UIView {

    func beginToast(msg:String,duration: TimeInterval =1.5) {

        letstyle = ToastStyle()

        makeToast(msg, duration: duration,position: .center, style: style)

    }

}

extension UIView: ToastViewProtocol  {}

限定了使用ToastViewProtocol协议的类是UIView,使用的时候用UIview的实例调用beginToast方法即可

相关文章

网友评论

      本文标题:protocol extension中where用法

      本文链接:https://www.haomeiwen.com/subject/fdfffrtx.html