【问题标题】:Why did Xcode warn me about making this a constant, and why does it still change?为什么 Xcode 警告我将其设为常量,为什么它仍然会改变?
【发布时间】:2022-01-16 10:39:28
【问题描述】:

在我的 updateBlob 函数中,Xcode 警告我 pos 没有更改,应该更改为 let 常量,即使我可以看到它正在更改,并且运行程序确实会更改位置值。当我使用 defer 关键字更新 BlobPos 类以在发送半径值时更新 x/y 坐标时,这一切似乎都发生了。虽然我可以避免使用 defer,但为什么编译器会警告我将 pos 设为常量,而程序仍然能够更改大概应该是常量的内容?

class BlobPos
{
    var x:CGFloat = 0
    var y:CGFloat = 0

    public init(radius:CGFloat) {

        defer {
            x = radius + 5
            y = radius + 5
        }
    }
}



class Blob
{
    
    var radius: CGFloat
    var pos: BlobPos
    
    init
    (
        radius: CGFloat,
        pos: BlobPos,
    )
    {
        self.radius = radius
        self.pos = pos
    }
    
}

func makeBlob() -> Blob
{
    
    let radius = 8
    
    let pos = BlobPos(radius:radius)
    
    return Blob(radius: radius, pos: pos)
}

func updateBlob(blob:Blob)
{

    let radius = blob.radius
    let pos    = blob.pos // compiler warning wanting me to turn this into a let constant instead of var

    pos.x += 6
    pos.y += 2
    
    blob.pos = pos // strangely, new position is set
    
}

【问题讨论】:

  • 你永远不会改变类,只会改变它的属性,所以“让”就足够了。如果“BlobPos”是一个结构,它需要一个“var”。

标签: swift class constants deferred let


【解决方案1】:

这是因为BlobPos 是一个类,更改类的属性不会更改其在内存中的位置,这就是类的传递方式(通过引用它们在内存中的位置)。如果BlobPos 是一个结构,那么您必须将它声明为一个变量,因为结构是通过它们的值传递的(而不是对其在内存中位置的引用)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-19
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    相关资源
    最近更新 更多