美文网首页
10.2 协议

10.2 协议

作者: LucXion | 来源:发表于2020-06-09 14:16 被阅读0次

    协议使用protocol关键字来创建,其中可以声明属性与方法。

    protocol Myprotocol{
        var name:String{get}
        var age:Int{get set}
        static var nikiName:String{set get}
        
        static func play()->Void
    }
    class Student:Myprotocol {
    //    在协议中声明set,在实现中既可以是只读的也可以是可读可写的。如果协议中约定的属性为可读可写,则在实现时其必须是可读可写的。
        var name: String
        var age:Int
        init() {
            name = ""
            age = 5
        }
        static var nikiName: String {
            set {
            }
            get {
                return "空"
            }
        }
        static func play() {
            print("do")
        }
    }
    func studentPlay(parama:Myprotocol){// 协议可以作为参数
        parama.age // 不可以调用协议中的静态部分
    }
    protocol MyTwo:Myprotocol {// 协议也可以继承
    }
    protocol MyClass:class {// 此协议只能被类遵守,不做限制的协议可以被类遵守
    }
    协议与扩展的配合使用
    //协议与扩展的运用
    // 协议方法
    protocol Myprotocol{
        func play()->Void
    }
    // 在延展中可以实现计算属性和方法
    extension Myprotocol {
        func play() -> Void {
            print("play")
        }
    }
    // 继承这个协议的类可以直接实现这个函数
    class Student:Myprotocol {
        
    }
    var stu = Student.init()
    stu.play()

    相关文章

      网友评论

          本文标题:10.2 协议

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