gpt4 book ai didi

swift - 在子类中调用例程

转载 作者:搜寻专家 更新时间:2023-11-01 05:32:24 26 4
gpt4 key购买 nike

我有一个用户定义的类映射,带有一个实例映射。 map 包含一个名为 squares 的用户定义对象的二维数组,类型为 Grid。 Grid 类包含一个名为 contains 的变量,它包含许多可能的用户定义类的一个对象。从 Grid 模块,我试图调用一个名为 Bug 的用户定义类中的函数。

执行此操作的正确语法是什么?

//within Class Grid

func GenerateImage() -> Int{

if self.containType == 1{
return self.contains.DisplayBug()
}else if self.containType == 2{
return 13
}else{
return 0
}
}

//within class Bug

func DisplayBug() -> Int{
if self.male == false{
return self.direction
}else{
if self.appearance == 1{
switch self.direction{
case 1:
return 5
case 2:
return 6
case 3:
return 7
case 4:
return 8
default:
return 0
}
}else if self.appearance == 2{
switch self.direction{
case 1:
return 9
case 2:
return 10
case 3:
return 11
case 4:
return 12
default:
return 0
}
}else{
return 0
}
}
}

最佳答案

由于您没有提供这些类的实现,因此我冒昧地制作了您拥有的类的示例结构:

class Grid {
let contains: SomeProtocol

init(contains: SomeProtocol) {
self.contains = contains
}
}

class Map {
let squares: [[Grid]]

init(squares: [[Grid]]) {
self.squares = squares
}
}

如您所见,contains 属性是 SomeProtocol 类型,其定义如下:

protocol SomeProtocol {
func displayBug()
}

接下来是实现此协议(protocol)的类(这只是一个示例,用于说明 displayBug 方法的实现可能会有所不同):

class Bug: SomeProtocol {
func displayBug() {
print("called from Bug")
}
}
class Foo: SomeProtocol {
func displayBug() {
print("called from Foo")
}
}
class Bar: SomeProtocol {
func displayBug() {
print("called from Bar")
}
}
class Buz: SomeProtocol {
func displayBug() {
print("called from Buz")
}
}

现在层次结构已经就位,我们可以对其进行测试:

let map = Map(squares: [
[
Grid(contains: Bug()),
Grid(contains: Foo())
],
[
Grid(contains: Bar()),
Grid(contains: Buz())
]
])

for gridArray in map.squares {
for grid in gridArray {
grid.contains.displayBug()
}
}

called from Bug

called from Foo

called from Bar

called from Buz

关于swift - 在子类中调用例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54749109/

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