swift - 全局函数调用协议(protocol)类型的变异方法。我怎样才能摆脱 var tmp 对象?

标签 swift protocols inout

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

关于swift - 全局函数调用协议(protocol)类型的变异方法。我怎样才能摆脱 var tmp 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53761485/

相关文章:

c - libcurl,用法 CURLOPT_REDIR_PROTOCOLS

MySQL 存储过程参数

ios - Xcode 8 Objective-C 类别警告

ios - 当我运行我的项目时,搜索栏不会出现在 UICollectionView 的标题中

swift - 如何在 Swift 中为泛型类创建单例

ios - 为什么 invalidateLayout 不触发 UICollectionView 中的 sizeForItemAtIndexPath? (附代码)

objective-c - 快速使用协议(protocol)和类名初始化对象

error-handling - 处理未知的网络协议(protocol)

swift - 如何将数组 block 传递给 inout 函数?类型删除?

vhdl - 避免在 VHDL 中使用 inout