非常基本的问题。我目前正在尝试以更面向对象的方式进行编码,但有些东西我不完全理解。我相信这不仅适用于 Swift,也适用于多种编程语言,因为我也在一些 PHP 代码中看到了这一点。
我的印象是,为了让您访问类中的方法,您需要创建一个实例,但我不确定当您将对象作为参数传递时会发生这种情况。
在moveDog(move:Animal)
方法下面的代码中获取一个Animal
对象作为参数,我不知道如何访问方法形成 Animal
对象而不先实例化该类 (print(move.run())
)?
声明本地参数时是否会发生实例化moveDog(move:Animal)
?我们可以说这与 let move = Animal()
是一样的吗?
class Animal{
func run(){
print("Running...")
}
}
class Dog{
func moveDog(move:Animal){
//how can the run method be called without
//having to instantiate Animal?
print(move.run())
}
}
let dog = Animal()
let buddy = Dog()
buddy.moveDog(dog)
最佳答案
初始化发生在您实际创建它时,例如让dog = Animal()
或让buddy = Dog()
。
简单说明一下,您可以通过使用继承来使用相同的 run()
函数来改进此代码,如下所示:
class Animal{
func run(){
print("Running...")
}
}
class Dog: Animal{
override func run() {
super.run()
}
}
let dog = Animal() //You don't need to instantiate this to use the Dog class
let buddy = Dog()
buddy.run()
在 swift 中,参数通常通过引用(结构除外)传递,而不是被复制。所以没有初始化传递参数。
关于swift - 当您将对象作为参数传递时,何时发生实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34437762/