需要方法参数的类型和协议 [英] Require type and protocol for method parameter

查看:111
本文介绍了需要方法参数的类型和协议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩Swift,并且偶然遇到以下问题:由于我有预定义的类 Animal

  //预定义类
class Animal {
var height:Float = 0.0
}
/ pre>

现在我们用构造函数接受动物写类 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 the Zoo wants every animal to have a name and hence defines the Namable 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 type Animal and conform to protocol Namable? And how do you declare that for the animals 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆