Nested types inside a protocol
Alternatively, you can have instance/type properties inside of a protocol that conform to another protocol:
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)
A protocol cannot require a nested type, but it can require an associated type that conforms to another protocol. An implementation could use either a nested type or a type alias to meet this requirement.
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
}