美文网首页
swift 协议方法可选

swift 协议方法可选

作者: 追忆之丘 | 来源:发表于2021-01-09 15:40 被阅读0次

swift 协议方法可选

protocol TextOptionalProtocol{
    //必须实现的方法
    func text()
    //可选实现的方法
    func textOption()
}
extension TextOptionalProtocol{
    func testOption() {
        print("可选协议")
    }
}

让一个类去实现这个协议

class TextOptionalProtocolClass: TextOptionalProtocol{
    func text() {
        print("Text")
    }
}

可选协议我们可以不用去实现,但是可以直接去调用testOption这个方法

let text = TextOptionalProtocolClass()
text.textOption()
// 可选协议

我们还可以在TextOptionalProtocolClass中重新实现一下textOption

class TextOptionalProtocolClass: TextOptionalProtocol{
    func text() {
        print("Text")
    }
    
    func textOption() {
        print("重新实现的方法")
    }
}
let text = TextOptionalProtocolClass()
text.textOption()
// 重新实现的方法

我们来测试一下我们常见的代理模式

class TextOptionalProtocolClass: TextOptionalProtocol{
    init(delegateText: DeleageText) {
        delegateText.delegate = self
    }
    
    func text() {
        print("Text")
    }
}

class DeleageText {
    var delegate: TextOptionalProtocol?
    func textDelegate(){
        delegate?.textOption()
    }
}
let delegateText = DeleageText()
let text = TextOptionalProtocolClass(delegateText: delegateText)
delegateText.textDelegate()
// 可选协议

我们让TextOptionalProtocolClass实现一下可选方法

class TextOptionalProtocolClass: TextOptionalProtocol{
    init(delegateText:DeleageText) {
        delegateText.delegate = self
    }
    
    func text() {
        print("Text")
    }
    
    func textOption() {
        print("重新实现的方法")
    }
}

class DeleageText{
    var delegate: TextOptionalProtocol?
    func textDelegate(){
        delegate?.textOption()
    }
}
let delegateText = DeleageText()
let text = TextOptionalProtocolClass(delegateText: delegateText)
delegateText.textDelegate()

相关文章

网友评论

      本文标题:swift 协议方法可选

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