ios - 在 Swift 中使用泛型数组作为参数的函数

标签 ios swift generics

我想制作一个以通用数组作为参数的通用函数。我有两个类 Animal 和 Bird 以及两个协议(protocol) Animals & Birds,我的方法参数符合这两个协议(protocol),但我无法添加到数组中。

protocol Birds {
    var canFly: Bool {get set}
}

protocol Animals {
    var name: String {get set}
    var legs: Int {get set}
}

class Animal: Animals {
    var name: String
    var legs: Int

    init(name: String, legs: Int) {
        self.name = name
        self.legs = legs
    }
}

class Bird: Birds {
    var canFly: Bool
    init(canFly: Bool) {
        self.canFly = canFly
    }
}

func myTestGenericMethod<T>(array: [T]) where T: Animals & Birds {
    for (index, _) in array.enumerated() {
        print("At last i am able to get both Animal and Bird")
    }
}

let cat = Animal(name: "cat", legs: 4)
let dog = Animal(name: "dog", legs: 4)
let crow = Bird(canFly: true)
myTestGenericMethod(array: [dog])

myTestGenericMethod(array: [cat, dog]) // Not Able to add this to array

最佳答案

当您编写 where T: Animals & Birds 时,T 必须从 Animals AND 扩展>鸟类

但是 catdog 并不是从 Animals AND Birds 扩展而来的>。所以这是个问题。

据我了解,您希望 T 必须从 Animals OR Birds 扩展而来。为此,我们必须有一个基础协议(protocol),AnimalsBirds 都是从该协议(protocol)扩展而来的。更改一点代码并修复它。

@objc protocol Base {
}

protocol Birds : Base {
  var canFly: Bool {get set}
}

protocol Animals : Base {
  var name: String {get set}
  var legs: Int {get set}
}

class Animal: Animals {
  var name: String
  var legs: Int

  init(name: String, legs: Int) {
    self.name = name
    self.legs = legs
  }
}

class Bird: Birds {
    var canFly: Bool
    init(canFly: Bool) {
      self.canFly = canFly
    }
  }

func myTestGenericMethod<T: Base>(array: [T]) {
  for object in array {
    if object is Bird {
      let bird = object as! Bird
      print(bird.canFly)
    } else if object is Animal {
      let animal = object as! Animal
      print(animal.name)
    }
  }
}

let cat = Animal(name: "cat", legs: 4)
let dog = Animal(name: "dog", legs: 4)
let crow = Bird(canFly: true)
myTestGenericMethod(array: [crow, cat, dog] as! [Base])
myTestGenericMethod(array: [cat, dog])

关于ios - 在 Swift 中使用泛型数组作为参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48018841/

相关文章:

ios - Ionic Cordova 应用程序在 iPad 上启动时崩溃

generics - 通用序列

generics - F# 中的严格泛型枚举转换

java - 从单个构造函数参数推断泛型类类型参数

ios - 具有自动调整大小的线性布局不起作用

iphone - UIActivityViewController 报告 "Remote compose controller timed out"

ios - 将设备方向设置为仅适用于 iPad 的横向

ios - 取消初始化加载 View Controller 的最佳方法?

ios - 设置一个carthage/cocoapod项目来分发多个依赖

swift - 如何使用 RACScheduler 创建循环 RACSignal