swift的协议扩展中有语法说明:
你可以使用协议扩展来给协议的任意方法或者计算属性要求提供默认实现。如果遵循类型给这个协议的要求提供了它自己的实现,那么它就会替代扩展中提供的默认实现。
import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        if let demo = self as? Demo {
            print(demo.sharedFrame)
        }
        print(self.sharedFrame)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
extension ViewController:Demo{
    var shardView: UIView {
        return self.view
    }
    var sharedFrame: CGRect{
        return CGRect(x: 0, y: 0, width: 30, height: 30)
    }
}
protocol Demo {
    var shardView:UIView{
        get
    }
}
extension Demo{
    var sharedFrame:CGRect{
        return shardView.frame
    }
}
上面这段代码打印的结果是不一样的
第一个打印的是 sharedView.frame的值
第二个打印的是 CGRect(x: 0, y: 0, width: 30, height: 30)的值
可以看出如果将对象转化成协议类型对象后,它所使用的将是协议的默认实现,和通常的类继承不同。









网友评论