swift - 协议(protocol)中的嵌套类型

标签 swift protocols swift-protocols

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

protocol Nested {

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

Xcode 显示“此处不允许输入”:

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

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

最佳答案

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

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
}

关于swift - 协议(protocol)中的嵌套类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31845066/

相关文章:

swift - 协议(protocol)只能用作通用约束,因为它具有 Self 或关联类型要求

swift - NSDateComponentsFormatter 输出在构建之间有所不同

ios - 需要将 firebase 远程配置中的值更新到我的 plist

calendar - 时间事件的 URI 方案

swift - 在 Swift 4 中,您能否编写仅适用于遵守多种协议(protocol)的事物的扩展?

swift 协议(protocol)扩展默认实现与类中的实际实现

iphone - 当标题、左按钮和右键已经存在时,将 UISearchBar 放入 UINavigationBar

swift 3 : Fast file path separation

ios - Swift 类的 Objective-c 协议(protocol)。无法识别的方法

swift - 我可以使一个结构或类多次符合通用协议(protocol)吗?