我想创建一个Swift Array的扩展,该扩展返回随机N个元素。

extension Array {
  func getRandomItems(max:Int) -> [T] {
    var randomItems = [T]()

    repeat
    {
      let randomNumber = Int(arc4random_uniform(UInt32(self.count)))
      if contains(randomItems, self[randomNumber]) {
        randomItems.append(self[randomNumber])
      }
    } while (randomItems.count < max)

    return randomItems
  }

}


print(["Canada","Brazil","China","Japan","U.S"].getRandomNumbers(3))


编译器说:“无法调用类型为([[T],T)的参数列表的'contains''”
如何使此功能起作用?

最佳答案

您需要确保只扩展符合Equatable的数组。另外,在最新的Beta中,T被替换为Element

extension Array where Element : Equatable {
  func getRandomItems(max:Int) -> [Element] {
    var randomItems = [Element]()

    repeat
    {
      let randomNumber = Int(arc4random_uniform(UInt32(self.count)))
      if randomItems.contains(self[randomNumber]) {
        randomItems.append(self[randomNumber])
      }
    } while (randomItems.count < max)

    return randomItems
  }

}


您的行if randomItems.contains(self[randomNumber])应该是if !randomItems.contains(self[randomNumber])

09-07 07:56