gpt4 book ai didi

swift - 从父类(super class)访问子类函数

转载 作者:行者123 更新时间:2023-11-30 11:31:55 25 4
gpt4 key购买 nike

有没有办法从父类(super class)访问子类方法?switch 语句位于父类(super class)的函数中。函数 createCityOne()、createCityTwo() 和 createCityThree() 等均位于其自己的子类中。

    if transitionSprite.name == nil || transitionSprite.name == "rd-d2c" || transitionSprite.name == "rd-f2c" || transitionSprite.name == "rd-c2c" {
print("city should come next")
switch randomIndex {
case 0:
cityOne.createCityOne()
print("1")
case 1:
cityTwo.createCityTwo()
print("2")
case 2:
print("3")
cityThree.createCityThree()
default:
break
}

最佳答案

你不能直接从父类(super class)访问子类方法,因为父类(super class)不知道它自己的子类的任何信息。

尽管如此,您始终可以尝试将事物转换为 Swift 中的事物,以获得其他类的功能。

看一下这个例子。这是非常基本和简单的,但我希望你能明白。

想象一下你有一个城市类:

class City {
func build() {
print("city is building")
}

它是 Town 的子类:

class Town: City {
func buildTown() {
print("town is building")
}
}

现在您希望从 City 类访问 Town 的 buildTown() 函数。因为 Town 始终是 City 因为它是子类,所以您可以创建如下内容:

class City {
func build() {
print("city is building")
}

func buildAnything() {
if self is Town {
(self as! Town).buildTown()
}
}
}

现在我并不是说您真的想要创建这样的东西,因为您以这种方式将子类的逻辑公开给父类(super class)。因此,解决此问题的一个好方法是仅创建一个 build() 函数,然后覆盖它。

class City {
func build() {
print("city is building")
}
}

class Town: City {
override func build() {
print("town is building")
}
}

因此,您可以从任何您想要的 City 子类访问相同的函数并自定义行为。

let myTown = Town()
let myCity = City()
myCity.build() //prints "city is building"
myTown.build() //prints "town is building"

好的解决方案始终取决于您的确切目标,因此请始终查看该语言提供的许多选项。有关继承的更多信息 here .

关于swift - 从父类(super class)访问子类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50167840/

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