需要方法参数的类型和协议 [英] Require type and protocol for method parameter
问题描述
我正在玩Swift,并且偶然遇到以下问题:由于我有预定义的类 Animal
:
//预定义类
/ pre>
class Animal {
var height:Float = 0.0
}
现在我们用构造函数接受动物写类
Zoo
。但Zoo
希望每个动物都有一个名称,因此定义Namable
协议。协议Namable {
var name:String {get}
}
class Zoo {
var animals:Animal [] = [];
}
如何写一个
addAnimal
方法,要求将作为参数传递的对象同时作为类型Animal
和符合协议 code> Namable ?你如何声明animals
数组?func addAnimal :(animal:????){...}
在目标C中, d写这样- (void)addAnimal:(Animal< Namable> *)animal {...}
解决方案其中有多个条件的子句。
func addAnimal< T:Animal where T:Nameable> :T){...}
修正案:
class Zoo< T:Animal where T:Nameable> {
var animals:T [] = []
func addAnimal(a:T){
...
}
}
I am playing around with Swift and am stumbling over the following problem: given I have the predefined class
Animal
://Predefined classes class Animal { var height: Float = 0.0 }
I now write the class
Zoo
with the constructor accepting animals. But theZoo
wants every animal to have a name and hence defines theNamable
protocol.protocol Namable { var name: String {get} } class Zoo { var animals: Animal[] = []; }
How would you write an
addAnimal
method that requires the object being passed as parameter to be both of typeAnimal
and conform to protocolNamable
? And how do you declare that for theanimals
array?func addAnimal:(animal: ????) { ... }
In Objective-C, I'd write something like this
- (void)addAnimal:(Animal<Namable>*)animal {...}
解决方案You can use a generic with a
where
clause with multiple conditions.func addAnimal<T: Animal where T: Nameable>(animal: T) { ... }
Amendment: You should probably make the whole class this generic so you can type the array properly
class Zoo<T: Animal where T: Nameable> { var animals : T[] = [] func addAnimal(a: T) { ... } }
这篇关于需要方法参数的类型和协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!