2024-11-21
class Enemy{
var health = 100
var attackStrength = 10
func move(){
print("Walk forward")
}
func attack(){
print("Land a hit, does \(attackStrength) damage.")
}
}
class Dragon: Enemy {
var wingSpan = 2
func talk(speech: String){
print("Says: \(speech)")
}
override func move() {
print("Fly forward")
}
override func attack() {
super.attack()
print("Spits fire, does 10 damage")
}
}
let skeleton = Enemy()
print(skeleton.health)
skeleton.move()
skeleton.attack()
let dragon = Dragon()
dragon.wingSpan = 5
dragon.attackStrength = 15
dragon.talk(speech: "My teeth are swords! My claws are spears! My wings are a hurricane")
dragon.move()
dragon.attack()
mutating func
,而class不用。因为安全拷贝的原因,苹果推荐优先使用Struct
,可以参考Choosing Between Structures and Classes