22

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

protocol Nested {

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

Xcode 说“此处不允许输入”

类型“NameOfClass”不能嵌套在协议“嵌套”中

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

4

3 回答 3

28

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

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
}
于 2015-08-06T02:12:49.300 回答
1

或者,您可以在符合另一个协议的协议内拥有实例/类型属性:

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)
于 2017-06-16T20:11:29.123 回答
0

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

protocol Nested {
    associatedtype NameOfClass: HasStringProperty

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

你可以像这样使用它

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

希望这可以帮助!

于 2017-05-23T17:02:12.723 回答