2016-03-29 69 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]> 
} 
相关问题