【问题标题】:Generic collection of X in Swift?Swift 中 X 的通用集合?
【发布时间】:2017-02-11 02:33:21
【问题描述】:

我正在尝试制定一个可以接受 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 准备的。

【问题讨论】:

    标签: swift generics swift3


    【解决方案1】:

    您需要将方法本身设为通用,并将类型参数用作“普通”参数的类型。然后,您还可以限制第一种类型的关联类型。比如:

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

    表示stuff 必须是Sequence,其元素类型符合或继承自Stuff

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-04
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      相关资源
      最近更新 更多