这是我的工作代码片段。但我想摆脱函数slide中的var tmp变量。
protocol Moveable {
mutating func move(to point: CGPoint)
}
class Car : Moveable {
var point:CGPoint = CGPoint(x: 23, y: 42)
func move(to point: CGPoint) {
self.point = point
print("Method move from class Car Point: \(point)")
}
}
struct Shape : Moveable {
var point:CGPoint = CGPoint(x: 23, y: 42)
mutating func move(to point: CGPoint) {
self.point = point
print("Method move from struct Shape Point:\(point)")
}
}
var prius: Car = Car()
var square: Shape = Shape()
func slide(slider: Moveable) {
var tmp = slider // <---- I want get rid of the tmp object.(
tmp.move(to: CGPoint(x: 100, y: 100))
}
slide(slider: prius)
slide(slider: square)
我已经尝试过类似的方法,以避免 var tmp:
func slide(slider: inout Moveable) {
slider.move(to: CGPoint(x: 100, y: 100))
}
slider(slider: prius) // <--- Compile Error
// Cannot use mutating member on immutable value: 'slider' is a 'let' constant
slider(slider: prius as (inout Moveable) // <--- Compile Error
谢谢你。