全局函数调用协议类型的变异方法。我怎样才能摆脱 var tmp 对象?
A global function calls a mutating method of a protocol type. How can I get rid of the var tmp object?
这是我的工作代码片段。
但是我想摆脱函数 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
谢谢。
它可能适用于这个小改动:
func slide<M: Moveable>(slider: inout M) {
slider.move(to: CGPoint(x: 100, y: 100))
}
我们不要求 Movable
,而是要求符合 Movable
.
的类型
并这样称呼它:
slide(slider: &prius)
slide(slider: &square)
这是我的工作代码片段。 但是我想摆脱函数 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
谢谢。
它可能适用于这个小改动:
func slide<M: Moveable>(slider: inout M) {
slider.move(to: CGPoint(x: 100, y: 100))
}
我们不要求 Movable
,而是要求符合 Movable
.
并这样称呼它:
slide(slider: &prius)
slide(slider: &square)