2015-08-06 12 views
14

Jest możliwe, że zagnieżdżone typy zadeklarowane wewnątrz protokołów, takich jak to:zagnieżdżone typy wewnątrz protokołu

protocol nested{ 

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

} 

Xcode że „Nie wpisuj tutaj dozwolony”, więc jeśli chcę utworzyć protokół które muszą mieć typ zagnieżdżony, nie jest to możliwe lub mogę to zrobić w inny sposób?

Odpowiedz

19

Protokół nie może wymagać typu zagnieżdżonego, ale może wymagać skojarzonego typu zgodnego z innym protokołem. Implementacja może użyć typu zagnieżdżonego lub aliasu typu, aby spełnić to wymaganie.

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 
} 
+0

Cool, ale nie rozumiem jednej rzeczy! Co oznacza typ kodu Nested = NotNested? – LettersBa

+1

Tworzy alias typu, aby spełnić wymagania 'Outera'. Istnieje teraz nowa nazwa 'NotNested', tak jakby była zagnieżdżona w' MyOtherClass'. Jeśli 'Outer' zadeklarował jakiekolwiek zastosowania' Zagnieżdżonego', prawdopodobnie mogło to zostać wywnioskowane przez kompilator. – ughoavgfhw

0

Oto kod, ale w sposób, który działa:

protocol Nested { 
    associatedtype NameOfClass: HasStringProperty 

} 
protocol HasStringProperty { 
    var property: String { get set } 
} 

I można go używać jak to

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

nadzieję, że to pomaga!

0

Alternatywnie, można mieć właściwości instancji/typ wewnątrz protokołu, że zgodne z innym protokołem:

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) 
Powiązane problemy