抱歉,标题确实很粗糙,但我正在 teamtreehouse.com 上学习 Swift 类(class),并且我做了一个“代码挑战”,回顾了面向对象的 Swift 类(class)。不管怎样,我提供了几个类,我的目标是子类化 Machine 类并重写该方法以实际执行某些操作,我就是这么做的。我通过了挑战,但很好奇我是否可以在传递参数后真正打印该函数的最终结果。
class Point {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
class Machine {
var location: Point
init() {
self.location = Point(x: 0, y: 0)
}
func move(_ direction: String) {
print("Do nothing! I'm a machine!")
}
}
// Enter your code below
class Robot: Machine {
override func move(_ direction: String) {
switch direction {
case "Up": location.y += 1
case "Down": location.y -= 1
case "Left": location.x -= 1
case "Right": location.x += 1
default: break
}
}
}
let aRobot = Robot()
aRobot.move("Up")
print(aRobot.location)
因此,最后 3 行是我实际管理此问题的尝试,但在控制台中,打印的是“Point”行,而不是所执行方法的实际结果。如果可能的话,我希望结果以坐标的形式打印。抱歉,可能有错误的代码,我只是一个初学者。提前致谢!
最佳答案
为了能够在 swift 中打印类型,您需要该类型符合 CustomStringConvertible
协议(protocol)。该协议(protocol)只有一个要求,即实现 description
var
extension Point: CustomStringConvertible {
var description: String {
return "(\(x), \(y))"
}
}
关于objective-c - 如何在 Swift 中打印此方法的最终结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42498671/