2016-03-29 68 views
2

有什麼辦法可以使用協議的泛型數組嗎? 例如,在Swift類的泛型中使用數組協議

/* I want to use protocol like below, 
* but I can't because protocol is not concrete 
* so cannot make array of it */ 
class MyClass<T where T:MyProtocol, T:[MyProtocol]> { 
    let result: T 
} 

protocol MyProtocol { 
    init(with: String) 
} 

class SpecialThing: MyProtocol { 
    let appleWatch: AppleWatch 

    init(with: String) { 
     self.appleWatch = AppleWatch(with) 
    } 
} 

class SampleClass { 
    func test { 
     typealias listCallback = (MyClass<[SpecialThing]>, NSError) ->() 
     typealias oneCallback = (MyClass<SpecialThing>, NSError) ->() 
    } 
} 

可以有一個對象或協議的子類的數組。 我認爲「typealias」不幫助我。

我想找到更簡單的方法.....

+0

,我不認爲這是可能有通用類型T指定爲MyProtocol和數組MyProtocol在同一時間。 – Lachezar

+0

我這麼認爲。我想在MyClass中初始化通用對象。研究一切,但仍然無法找到解決方案。 – macaron

+0

不可能,因爲我知道。很明顯,但我知道的唯一「解決方案」是class MyClass 讓結果:[T] } –

回答

1

我這個第一個問題是類型簽名是錯誤的:

class MyClass<T where T:MyProtocol, T:[MyProtocol]> 

這是同類型的東西做的:

let t: String 
let t: [String] 
t = String("foo") 

編譯器會抱怨,因爲您正在重新定義T,一次作爲MyProtocol,再次爲MyProtocol數組。你不能擁有兩個,你只能擁有一個。

0

答:所述的構建類似Either

enum Either<T, U> 
{ 
    case Left(T) 
    case Right(U) 

    var leftValue: T? 
    { 
     if case .Left(let leftValue) = self 
     { 
      return leftValue 
     } 

     return nil 
    } 

    var rightValue: U? 
    { 
     if case .Right(let rightValue) = self 
     { 
      return rightValue 
     } 

     return nil 
    } 
} 

允許:

class MyClass<T: MyProtocol> 
{ 
    let result: Either<T, [MyProtocol]> 
} 
相關問題