如何在Swift 3的子类中重写Init()

时间:2017-04-10 20:54:51

标签: ios swift swift3 initialization subclass

我还是Swift的初学者。我有一个类NonPlayerCharacter作为父类和从它继承的子类Goblin。我在NonPlayer类中定义了健康和力量,并在Goblin中定义了武器。然后我宣布一个新的变量,所以我可以调用类Goblin并改变健康,力量和武器的值,但我看不到支架内的武器(我只看到健康和力量)。我尝试创建一个init函数,但是我收到了这个错误“在从初始化程序返回之前没有在所有路径上调用Super.init”。我在代码中的下面的评论中更清楚地解释了我的问题。

我在Playground上有这个课程

class NonPlayerCharacter 
{

  var health: Int
  var power: Int

init() {

    health = 0
    power = 0

}
 init(health: Int , power : Int) {
    self.health = health
    self.power = power

}

func attack () -> String
{
    return "attack from NonPlayer Character"

}    }

var NonPlayerMethod = NonPlayerCharacter(health: 100, power: 90)

 //and this is the SubClass: 

  class Goblin: NonPlayerCharacter
   {
  var weapon : Int = 0

  override func attack() -> String {
    return "attack from Goblin"
 }
 }



 var GoblinMethod = Goblin(health: 40, power: 12)
 GoblinMethod.weapon = 10
 GoblinMethod.attack()

  //I tried to make initialization like this in the SubClass** 


   class Goblin: NonPlayerCharacter
  {
   var weapon : Int = 0

   Init ( weapon: Int )
   {
   self.weapon = weapon 
   }
   }

   // so I can change the values like this :

   var GoblinMethod = Goblin( weapon: 30 , health: 20, power: 50) 

  // I got this error ( Super.init isn't called on all paths before returning from initializer )
 //I don't think I need to override Init as the weapon only in the SubClass.

2 个答案:

答案 0 :(得分:3)

所以你有两种方法来处理你的案子:

1为您的子类创建一个自己的初始值设定项,调用超级初始化程序,然后初始化此类武器属性

class Goblin: NonPlayerCharacter {
  var weapon : Int = 0

  init(health: Int, power: Int, weapon: Int) {
    super.init(health: health, power: power)
    self.weapon = weapon
  }

  override func attack() -> String {
    return "attack from Goblin"
  }
}

然后你就可以像这样创造一个地精:

var goblin1 = Goblin(health: 30, power: 20, weapon: 50)

2为您的子类创建一个便利初始化程序,以便能够决定是否只调用父类的初始化程序(设置运行状况和功率)或方便的(设置运行状况,电源和武器),如下所示:

class Goblin: NonPlayerCharacter {
  var weapon : Int = 0

  convenience init(health: Int, power: Int, weapon: Int) {
    self.init(health: health, power: power)
    self.weapon = weapon
  }

  override func attack() -> String {
    return "attack from Goblin"
  }
}

然后你就可以像这样创造一个地精:

var goblin2 = Goblin(health: 30, power: 20, weapon: 50)

或者像这样:

var goblin3 = Goblin(health: 30, power: 20)

进一步阅读herehere

答案 1 :(得分:0)

我这样解决了。它有效,但我不知道在使用“方便初始化”之间哪一个更好。而不是使用。

class NonPlayer {
   private var health: Int
   private var power: Int
   init(health: Int, power: Int) {
    self.health = health
    self.power = power
   }

   func attack() {
    print ("비유저에게 공격당했습니다.")
   }
}

class Goblin: NonPlayer {
    private var weaponDamage: Int
    init(health: Int, power: Int, weaponDamage: Int) {
      self.weaponDamage = weaponDamage
      super.init(health: health, power: power)
    }
    override func attack() {
     print("고블린에게 공격당했습니다.")
    }
}

let goblin = Goblin(health: 200, power: 15, weaponDamage: 20)
goblin.attack()