可以在协议(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/