![](/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.