![](/img/trans.png)
[英]Swift Generics: function with T.Type as parameter returns optional T
[英]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 & Birds
写where T: Animals & Birds
,必须从Animals
与 Birds
扩展T
但是cat
与dog
是不是来自延长Animals
和 Birds
。 所以这是问题。
据我了解,您希望T
必须从Animals
或 Birds
扩展。 要做到这一点,我们必须有一个扩展了Animals
和Birds
的基本协议。 更改一些代码并修复它。
@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.