协议内的嵌套类型

时间:2015-08-06 00:45:47

标签: swift protocols swift-protocols

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

startx chromium --kiosk --

Xcode说"这里不允许输入" ,所以,如果我想创建一个需要嵌套类型的协议,这是不可能的,或者我可以做这用其他方式?

3 个答案:

答案 0 :(得分:23)

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

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
}

答案 1 :(得分: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)

答案 2 :(得分:0)

以下是您的代码,但其作用方式有效:

protocol Nested {
    associatedtype NameOfClass: HasStringProperty

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

你可以像这样使用它

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

希望这有帮助!

相关问题