gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:56:03 32 4
gpt4 key购买 nike

我想制作一个以通用数组作为参数的通用函数。我有两个类 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com