简体   繁体   中英

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

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

eg

protocol MyDelegate: class {

}

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.)

From the Apple docs:

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

Example:

protocol AProtocol: class {   
}

//Following line will produce error: Non-class type 'aStruct' cannot conform to class protocol 'AProtocol'
struct aStruct: AProtocol { 
}

The line declaring the structure will spit an error. Following line will produce error:

Non-class type ' aStruct ' cannot conform to class protocol ' AProtocol '

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM