2

Can anyone explain the following protocol syntax:

protocol AddItemViewControllerDelegate: class {
  func addItemViewControllerDidCancel(_ controller: AddItemViewController)
  func addItemViewController(_ controller: AddItemViewController,
                     didFinishAdding item: ChecklistItem)
}

What does "class" do?

Hamish
  • 78,605
  • 19
  • 187
  • 280
7stud
  • 46,922
  • 14
  • 101
  • 127

1 Answers1

3

It means that the protocol can be adopted only by classes. So no Structure or Enum can adopt this protocol.

Class-Only Protocols

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
}

In the example above, SomeClassOnlyProtocol can only be adopted by class types. It’s a compile-time error to write a structure or enumeration definition that tries to adopt SomeClassOnlyProtocol.

NOTE

Use a class-only protocol when the behavior defined by that protocol’s requirements assumes or requires that a conforming type has reference semantics rather than value semantics. For more on reference and value semantics, see Structures and Enumerations Are Value Types and Classes Are Reference Types.

Reference: Swift Programming Language - Protocols

Community
  • 1
  • 1
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
  • Thanks. There doesn't appear to be anything about using "class" for that purpose in Apple's Swift language [guide](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID267). In the [protocol section](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID267), the guide mentions using AnyObject for that purpose. – 7stud Dec 17 '17 at 10:56
  • @7stud: You are correct, I think in the previous versions of that document they were using `class` keyword. The purpose is same, but don't know why the change in keywords. Will do a research on that :) – Midhun MP Dec 17 '17 at 11:02
  • Your quote from the reference does not mention `: class`. It seems that Apple changed the documentation (compare this older answer: https://stackoverflow.com/a/32118452/1187415 from the linked-to duplicate targets). – See https://stackoverflow.com/questions/30176814/whats-the-difference-between-a-protocol-extended-from-anyobject-and-a-class-onl about why it is (apparently) the same. – Martin R Dec 17 '17 at 11:03
  • @MartinR: I've read the previous docs of Apple Swift, in that they have used class instead of AnyObject (I clearly remember that). Thanks for the second link, I got a clear idea about it now. – Midhun MP Dec 17 '17 at 11:08