- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有一个用户定义的类映射,带有一个实例映射。 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/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!