如何将Object / Class作为函数的参数

时间:2016-07-24 02:28:10

标签: swift

假设我有这个猫类,我做了2个实例。我希望猫可以互相攻击

class ninjaCat {
   var health : Double = 100.00
   var attack = Double()

   init(attack : Double){
      self.attack = attack
   }

   func thunderClaw(otherCat : ninjaCat){
      health = otherCat.health
      otherCat.health = health - self.attack
   }
}

var NinjaCat1 = ninjaCat(10.60)
var NinjaCat2 = ninjaCat(20.15)

NinjaCat1.thunderClaw(NinjaCat2)

将类对象作为函数参数传递是否可行?

1 个答案:

答案 0 :(得分:2)

确实可能。但是你应该检查你的代码,因为你使用攻击猫的当前生命而不是目标来计算剩余寿命:

x86_64

应该是

func thunderClaw(otherCat : ninjaCat){
   otherCat.health = health - self.attack
}

或只是

func thunderClaw(otherCat : ninjaCat){
   otherCat.health = otherCat.health - self.attack
}