10.2 协议

2020-06-09  本文已影响0人  LucXion

协议使用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()
上一篇下一篇

猜你喜欢

热点阅读