gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:12:08 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com