协议内的嵌套类型

Let*_*sBa 18 protocols swift swift-protocols

可以在协议中声明嵌套类型,如下所示:

protocol Nested {

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

}
Run Code Online (Sandbox Code Playgroud)

Xcode说"Type not allowed here",所以,如果我想创建一个需要嵌套类型的协议,这是不可能的,或者我可以用其他方式做到这一点?

ugh*_*fhw 24

协议不能要求嵌套类型,但它可能需要符合其他协议的关联类型.实现可以使用嵌套类型或类型别名来满足此要求.

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
}
Run Code Online (Sandbox Code Playgroud)