作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我想制作一个以通用数组作为参数的通用函数。我有两个类 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 扩展>鸟类
但是 cat
和 dog
并不是从 Animals
AND Birds
扩展而来的>。所以这是个问题。
据我了解,您希望 T
必须从 Animals
OR Birds
扩展而来。为此,我们必须有一个基础协议(protocol),Animals
和 Birds
都是从该协议(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/
我是一名优秀的程序员,十分优秀!