2015-08-06 1 views
14

Il est possible d'avoir des types imbriqués déclarés dans les protocoles, comme ceci:types Imbriqué dans un protocole

protocol nested{ 

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

} 

Xcode disent que « type non autorisé ici », donc, si je veux créer un protocole qui doit avoir un type imbriqué, ce n'est pas possible ou je peux le faire d'une autre manière?

Répondre

19

Un protocole ne peut pas nécessiter de type imbriqué, mais il peut nécessiter un type associé conforme à un autre protocole. Une implémentation peut utiliser un type imbriqué ou un alias de type pour répondre à cette exigence.

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, mais ne comprend pas une chose! Qu'est-ce que le code typealias Nested = NotNested signifie? – LettersBa

+1

Il crée un alias de type pour répondre aux exigences de 'Outer'. Il y a maintenant un nouveau nom pour 'NotNested' comme s'il était imbriqué dans' MyOtherClass'. Si 'Outer' a déclaré des utilisations de' Nested', cela pourrait probablement être déduit par le compilateur. – ughoavgfhw

0

Voici votre code, mais d'une manière qui fonctionne:

protocol Nested { 
    associatedtype NameOfClass: HasStringProperty 

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

Et vous pouvez l'utiliser comme ceci

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

Hope this helps!

0

Vous pouvez également avoir des propriétés instance/de type à l'intérieur d'un protocole conforme à un autre protocole:

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)