LettersBa LettersBa - 7 months ago 189
Swift Question

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 say that "Type not allowed here", so, if I want to create a protocol that need to have a nested type, this is not possible or I can do this in other way?

Answer

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
}
Comments