【问题标题】:Nested types inside a protocol协议中的嵌套类型
【发布时间】:2015-08-06 00:45:46
【问题描述】:

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

protocol Nested {

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

Xcode 说 “此处不允许输入”

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

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

【问题讨论】:

    标签: swift protocols swift-protocols


    【解决方案1】:

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

    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
    }
    

    【讨论】:

    • 酷,但不明白一件事!代码 typealias Nested = NotNested 是什么意思?
    • 它创建一个类型别名以满足Outer的要求。 NotNested 现在有了一个新名称,就好像它嵌套在 MyOtherClass 中一样。如果Outer 声明了Nested 的任何用途,这可能是由编译器推断出来的。
    【解决方案2】:

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

    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)
    

    【讨论】:

      【解决方案3】:

      这是您的代码,但在某种程度上是有效的:

      protocol Nested {
          associatedtype NameOfClass: HasStringProperty
      
      }
      protocol HasStringProperty {
          var property: String { get set }
      }
      

      你可以这样使用它

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

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-01-25
        • 1970-01-01
        • 2020-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多