Search code examples
swiftprotocolsswift-protocols

Nested types inside a protocol


It is possible to have nested types declared inside protocols, like this:

protocol Nested {

    class NameOfClass {
        var property: String { get set }
    }
}

Xcode says "Type not allowed here":

Type 'NameOfClass' cannot be nested in protocol 'Nested'

I want to create a protocol that needs to have a nested type. Is this not possible or I can do this in another other way?


Solution

  • A protocol cannot require a nested type, but it can require an associated type that conforms to another protocol. An implementation could use either a nested type or a type alias to meet this requirement.

    protocol Inner {
        var property: String { get set }
    }
    protocol Outer {
        associatedtype Nested: Inner
    }
    
    class MyClass: Outer {
        struct Nested: Inner {
            var property: String = ""
        }
    }
    
    struct NotNested: Inner {
        var property: String = ""
    }
    class MyOtherClass: Outer {
        typealias Nested = NotNested
    }