1

这是我的工作代码片段。但我想摆脱函数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

谢谢你。

4

1 回答 1

4

它可能适用于这个小改动:

func slide<M: Moveable>(slider: inout M) {
    slider.move(to: CGPoint(x: 100, y: 100))
}

我们没有要求,而是要求Movable符合的类型Movable

并这样称呼它:

slide(slider: &prius)
slide(slider: &square)
于 2018-12-13T12:17:36.483 回答