相关疑难解决方法(0)

需要方法参数的类型和协议

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

//Predefined classes
class Animal {
    var height: Float = 0.0
}
Run Code Online (Sandbox Code Playgroud)

我现在Zoo用接受动物的构造函数编写类.但是Zoo希望每只动物都有一个名字,因此定义了Namable协议.

protocol Namable {
    var name: String {get}
}

class Zoo {
    var animals: Animal[] = [];
}
Run Code Online (Sandbox Code Playgroud)

您如何编写一个addAnimal方法,要求将对象作为参数传递为类型 Animal符合协议 Namable?你如何为animals阵列声明?

    func addAnimal:(animal: ????) { ... }
Run Code Online (Sandbox Code Playgroud)

在Objective-C中,我会写这样的东西

    - (void)addAnimal:(Animal<Namable>*)animal {...}
Run Code Online (Sandbox Code Playgroud)

xcode cocoa protocols ios swift

26
推荐指数
1
解决办法
5922
查看次数

标签 统计

cocoa ×1

ios ×1

protocols ×1

swift ×1

xcode ×1