Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested types inside a protocol

Tags:

It is possible to have nested types declared inside protocols, like this:

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

Xcode says "Type not allowed here":

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

I want to create a protocol that needs to have a nested type. Is this not possible or I can do this in another other way?

like image 622
LettersBa Avatar asked Aug 06 '15 00:08

LettersBa


1 Answers

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 } 
like image 183
ughoavgfhw Avatar answered Nov 03 '22 00:11

ughoavgfhw