Class-Only Protocols

suggest change

A protocol may specify that only a class can conform to it by putting class in its inheritance list. That keyword must appear before any other inherited protocols. In Swift 4 and later, write AnyObject instead of class.

protocol ClassOnlyProtocol: class {
    // class-only requirements
}

If a non-class type tries to implement ClassOnlyProtocol, a compiler error will be generated.

struct MyStruct: ClassOnlyProtocol { 
    // error: Non-class type 'MyStruct' cannot conform to class protocol 'ClassOnlyProtocol'  
}

Other protocols may inherit from the ClassOnlyProtocol, but they will have the same class-only requirement.

protocol MyProtocol: ClassOnlyProtocol {
    // ClassOnlyProtocol Requirements
    // MyProtocol Requirements
}

class MySecondClass: MyProtocol {
    // ClassOnlyProtocol Requirements
    // MyProtocol Requirements
}

Reference semantics of class-only protocols

Using a class-only protocol allows for reference semantics when the conforming type is unknown.

protocol Foo : class {
    var bar : String { get set }
}

func takesAFoo(foo:Foo) {

    // this assignment requires reference semantics,
    // as foo is a let constant in this scope.
    foo.bar = "new value"
}

In this example, as Foo is a class-only protocol, the assignment to bar is valid as the compiler knows that foo is a class type, and therefore has reference semantics.

If Foo were not class-only, this would be an error. The conforming type might be a value type, which must be a var to be mutated.

protocol Foo {
    var bar : String { get set }
}

func takesAFoo(foo: Foo) {
    foo.bar = "new value" // error: Cannot assign to property: 'foo' is a 'let' constant
}

Copy the argument into a var when the protocol is not class-only:

func takesAFoo(foo: Foo) {
    var foo = foo
    foo.bar = "new value" // mutates the local copy only
}

Weak variables of protocol type

When applying the weak modifier to a variable of protocol type, that protocol type must be class-only, as weak can only be applied to reference types.

weak var weakReference : ClassOnlyProtocol?

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents