swift 4.2 官方文档学习笔记(十四)- Protocol

Sellen Wei
1 min readDec 23, 2018

--

谁可以继承protocol?class,struct和enum都可以继承protocol,而且可以继承不止一个协议

那么protocol里面一般定义一些什么呢?

  1. 未被实现的方程
  2. 未被赋值的property

3. 结构体和枚举是值类型。默认情况下,值类型的属性不能在它的实例方法中被修改。如果要在某个function中修改属性的值就必须要在这个function前使用mutating关键词,因此如果想在struct或者enum中使用某些protocol的function,并在function实现中修改变量,就要在这些可能会被继承并实现的方程前面加上mutating:

如果是class继承了togglable这个protocol,则不需要加上mutating关键词。

4. protocol init() 在protocol中声明构造器,在class继承这个protocol的时候,要在前面加上required关键词

5. Protocols as Types: Protocol是一种类型,也就是可以被当作跟Int,String一样的type类型来使用

6.protocol也经常和delegation合作使用,但注意delegate在声明时,一定要是weak指针

7.extension也同样可以用于class继承额外的protocol,虽然我认为这部分应该放在extension章节,似乎跟protocol关系不大。

8. Conditionally Conforming to a Protocol

9. Declaring Protocol Adoption with an Extension(这个简单来说就是class已经包括了所有protocol的函数或者property,这时候只要extension一个空的protocol就可以了,我的理解是这样有利于code的方便理解,也变相将class的type进行了扩展,Hamster以后就可以当作TextRepresentable type来使用了)

11. protocol可以继承一个或者多个protocol,中间用逗号分开

12.Class-Only Protocols, 用AnyObject修饰的protocol只能被class继承,不能被struct和enum继承

13. Protocol Composition:It doesn’t matter which specific type is passed to the function, as long as it conforms to both of the required protocols.

14.Checking for Protocol Conformance:

The is operator returns true if an instance conforms to a protocol and returns false if it doesn’t.

The as? version of the downcast operator returns an optional value of the protocol’s type, and this value is nil if the instance doesn’t conform to that protocol.

The as! version of the downcast operator forces the downcast to the protocol type and triggers a runtime error if the downcast doesn’t succeed.

15. Optional Protocol Requirements:(如果class继承了protocol,那么一定要implement所有protocol的方程的,但是!如果加上@objc optional关键词,则不一定非要implement该方程,但是在使用时,由于不确定方程是否存在,一律都要加?)

16. Providing Default Implementations: Protocol requirements with default implementations provided by extensions are distinct from optional protocol requirements. Although conforming types don’t have to provide their own implementation of either, requirements with default implementations can be called without optional chaining.

17. Adding Constraints to Protocol Extensions: 只有特定条件满足,protocol才可以被extension

问题:这里有个疑问,不知道继承了protocol之后的class,能否downcasting,比如let A = protocol as?class 由于code比较复杂,不想在这里尝试,以后工作当中如果用到可以试一次。

--

--