objective-c - 如何在 Swift 中打印此方法的最终结果?

标签 objective-c swift xcode class methods

抱歉,标题确实很粗糙,但我正在 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/

相关文章:

objective-c - NSWindow 不响应击键命令 -s

arrays - Swift 3 - 将用户输入添加到数组并选择随机项目

ios - Swift:CoreData 和通用的 NSOrderedSet

objective-c - 时间以毫秒为典型时间格式

ios - 单击 TableView 中的图像

objective-c - UINavigationBar 后退按钮可拉伸(stretch)图像太长

ios - 如何使用 ArcGIS sdk for iOS 计算坐标数组的缩放或 mapScale

iphone - IOS按钮按下事件?

c++ - 在 .mm 文件中无法识别预编译 header 中的#define

ios - 如何在 iOS 中将对象传递给 NextViewController?