What's the difference between a protocol extended from AnyObject and a class-only protocol?

前端 未结 6 1915
一整个雨季
一整个雨季 2020-12-02 14:30

Both this declaration

protocol SomeProtocol : AnyObject {
}

and this declaration

protocol SomeProtocol : class {
}
<         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 14:34

    In the Swift programming language guide for protocols, under the Class-Only Protocols section. It only mentioned AnyObject, but not class.

    You can limit protocol adoption to class types (and not structures or enumerations) by adding the AnyObject protocol to a protocol’s inheritance list.

    protocol SomeClassOnlyProtocol: AnyObject, SomeInheritedProtocol {
        // class-only protocol definition goes here
    }
    

    For that reason, I will suggest using AnyObject over class for new code or new project. Other than that, I don't see any obvious difference between them.

提交回复
热议问题