2017-02-11 36 views
2

我试图制定,可以采取X类型的对象集合在一个委托协议,该协议的同样的方法应该能够采取的实例:X在Swift中的通用集合?

  • Set<X>
  • Array<X>
  • LazyMapCollection<Dictionary<_, X>, X>(这最后一个是从Dictionary.values

的问题是,如何声明协议方法?

以下是一些没有工作相当合适的人选方法声明:

public protocol BlahDelegate : NSObjectProtocol { 
    // won't compile; 'cannot specialize generic type "Sequence"' 
    func blah(_ sender: Blah,foundStuff stuff: Sequence<Stuff>) 

    // won't compile; 'cannot specialize generic type "Collection"' 
    func blah(_ sender: Blah,foundStuff stuff: Collection<Stuff>) 

    // this can't take in Set<Stuff> nor LazyMapCollection<Dictionary<_, Stuff>, Stuff> 
    func blah(_ sender: Blah,foundStuff stuff: Array<Stuff>) 

    // this can't take in Array<Stuff> nor LazyMapCollection<Dictionary<_, Stuff>, Stuff> 
    func blah(_ sender: Blah,foundStuff stuff: Set<Stuff>) 
} 

PS:这是斯威夫特3.

回答

5

您将需要使该方法本身一般,和使用类型参数作为“正常”参数的类型。然后您也可以限制第一种类型的关联类型。因此,例如:

func blah<T>(stuff: T) where T : Sequence, T.Iterator.Element : Stuff 

意味着stuff必须是Sequence其元素类型是什么,符合或Stuff继承。