创建一个主要对象并为每个主对象创建宠物的程序

时间:2015-06-15 22:10:42

标签: swift oop

我是快速编码的新手,我想知道如何创建一个程序来创建一个主要对象并为每个对象创建一个宠物。你会使用字符串,数组还是什么?

1 个答案:

答案 0 :(得分:0)

以下是一个处理宠物的快速程序示例。我在here找到了它。

它有一个协议Animal,它定义动物的部分,有int腿,布尔驯化。

protocol Animal {

    var legs: Int { get set }
    var domesticated: Bool { get }

    func hasFur() -> String
    func countLegs() -> String

}

然后协议Pet是一个动物。 需要定义的变量,牵引,pettable,foodType和名称。

protocol Pet : Animal {
    var leashed: Bool { get set }
    var pettable: Bool { get set }
    var foodType: String { get set }
    var name: String { get set }

}

然后班级狗是宠物。变量定义为leg,domesticated,leashed,pettable和foodType。 你仍然要担心名字。 您有Animal函数hasFur()和countLegs()的实现。

class Dog: Pet {
    var legs = 4
    let domesticated = true
    var leashed = true
    var pettable = true
    var foodType = "Kibble"
    var name = ""

    func hasFur() -> String {
            return "The dog is furry"
    }

    func countLegs() -> String {
        return "\(name) the dog has \(legs) legs"
    }    
}

这是"主要"当你在任何IDE中运行时,你将运行。

let Fido = Dog()
Fido.name = "Ralph"
Fido.legs = 3
Fido.countLegs() // Prints “Ralph the dog has 3 legs”

println(Fido.foodType) // Prints “Kibble”