In Swift, what does it mean for protocol to inherit from class keyword?

后端 未结 2 481
悲&欢浪女
悲&欢浪女 2020-12-09 22:54

In Swift, what does it mean for protocol to inherit from class keyword?

e.g.

protocol MyDelegate: class {

}
2条回答
  •  Happy的楠姐
    2020-12-09 23:14

    The gist of Starscream's answer is correct, but it misses the why which I think is important here. It comes down to ARC and memory management.

    Swift is a language of reference types and value types. Classes are reference types, while everything else is a value type. Effectively, we're not really specifying that the protocol inherits from class... it's more like we're specifying that the protocol can only be implemented by reference types.

    And why is that important?

    It's important, because without it, we can't use the weak keyword with the protocol.

    protocol ExampleProtocol {}
    
    class DelegatedClass {
        weak var delegate: ExampleProtocol?
    }
    

    This generates the error:

    'weak' cannot be applied to non-class type 'ExampleProtocol'

    And why not? Because the weak keyword only makes sense with reference types to which ARC applies. ARC does not apply to value types. And without specifying our protocol with class, we cannot guarantee that our delegate property is set to a reference-type. (And if we don't use weak, we're most likely creating a retain cycle.)

提交回复
热议问题