gpt4 book ai didi

ios - 如何在 Swift 3 的子类中覆盖 Init()

转载 作者:行者123 更新时间:2023-11-28 10:56:15 25 4
gpt4 key购买 nike

我仍然是 Swift 的初学者。我有一个类 NonPlayerCharacter 作为父类和一个从它继承的子类 Goblin。我在 NonPlayer 类中定义了 health 和 power,在 Goblin 类中定义了 weapon。然后我声明一个新变量,这样我就可以调用类 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.

最佳答案

所以你有两种方法来处理你的情况:

1 为您的子类创建一个自己的初始化器,调用 super 初始化器,然后像这样初始化武器属性

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

关于ios - 如何在 Swift 3 的子类中覆盖 Init(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43332739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com