协议中的嵌套类型

Nested types inside a protocol

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

protocol Nested {

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

Xcode 说 "Type not allowed here":

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

我想创建一个需要嵌套类型的协议。这是不可能的还是我可以用其他方式做到这一点?

协议不能要求嵌套类型,但它可以要求符合另一个协议的关联类型。实现可以使用嵌套类型或类型别名来满足此要求。

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
}

这是您的代码,但以一种有效的方式:

protocol Nested {
    associatedtype NameOfClass: HasStringProperty

}
protocol HasStringProperty {
    var property: String { get set }
}

你可以这样使用它

class Test: Nested {
    class NameOfClass: HasStringProperty {
        var property: String = "Something"
    }
}

希望对您有所帮助!

或者,您可以在符合另一个协议的协议中拥有 instance/type 属性:

public protocol InnerProtocol {
    static var staticText: String {get}
    var text: String {get}
}

public protocol OuterProtocol {
    static var staticInner: InnerProtocol.Type {get}
    var inner: InnerProtocol {get}
}

public struct MyStruct: OuterProtocol {
    public static var staticInner: InnerProtocol.Type = Inner.self
    public var inner: InnerProtocol = Inner()

    private struct Inner: InnerProtocol {
        public static var staticText: String {
            return "inner static text"
        }
        public var text = "inner text"
    }
}

// for instance properties
let mystruct = MyStruct()
print(mystruct.inner.text)

// for type properties
let mystruct2: MyStruct.Type = MyStruct.self
print(mystruct2.staticInner.staticText)