Swift中X的通用集合?

时间:2017-02-11 02:33:21

标签: swift generics swift3

我正在尝试制定一个委托协议,该协议可以接收X类型的对象集合。此协议的相同方法应该能够采用以下实例:

  • 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:这是针对Swift 3的。

1 个答案:

答案 0 :(得分:6)

您需要使方法本身具有通用性,并使用type参数作为&#34; normal&#34;的类型。参数。然后,您还可以限制第一种类型的关联类型。例如:

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

表示stuff必须是Sequence,其元素类型符合Stuff或从// change this var avatar = new Sprite(150, 150, avatarImage); // to this var avatar = new Sprite(avatarImage, 150, 150); 继承。