繁体   English   中英

Swift中以泛型数组作为参数的函数

[英]Function with Array of Generics as Parameter in Swift

我想做一个将泛型数组作为参数的泛型函数。 我有两个类Animal和Bird以及两个协议Animals&Birds,并且我的方法参数符合这两个协议,但是我无法添加到数组中。

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 & Birdswhere T: Animals & Birds ,必须从Animals Birds扩展T

但是catdog是不是来自延长Animals Birds 所以这是问题。

据我了解,您希望T必须从Animals Birds扩展。 要做到这一点,我们必须有一个扩展了AnimalsBirds的基本协议。 更改一些代码并修复它。

@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])

在您的代码中where T: Animals & Birds意味着您需要T为同时符合两种协议的实例。 但是您没有符合这两种协议的类。 如果创建一个实例,则可以在通用方法中使用其实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM