'self' 在struct中初始化所有存储的属性之前使用

'self' used before all stored properties are initialized in struct

我希望 CurrendData.locationCurrentData 初始化后获得它​​的随机值。我想出了以下代码:

struct CurrentData {
    var size: (x: Int, y: Int)
    var location: (x: Int, y: Int)
        
    init(size: (x: Int, y: Int)) {
        self.size = size
        self.location = (getRandom(size.x), getRandom(size.y)) //error
    }
    
    private func getRandom (_ value:Int) -> Int {
        return Int.random(in: 0...value-1)
    }
}

但我收到此错误:“'self' 在所有存储的属性初始化之前使用”。如何修复?

getRandom是一个实例方法,所以它在self上被调用(但是,Swift允许你在访问实例methods/properties时省略self) .

如果您希望能够从 init 调用函数,您需要将其声明为 static 方法而不是实例方法。然后,您可以通过写出类型名称 (CurrentData) 或简单地使用 Self.

来调用静态方法
struct CurrentData {
    var size: (x: Int, y: Int)
    var location: (x: Int, y: Int)
        
    init(size: (x: Int, y: Int)) {
        self.size = size
        self.location = (Self.getRandom(size.x), Self.getRandom(size.y))
    }
    
    private static func getRandom (_ value:Int) -> Int {
        Int.random(in: 0...value-1)
    }
}

而不是将 getRandom 定义为实例方法,将其定义为静态方法,然后通过类型名称 (CurrentData) 或 Self

引用它
struct CurrentData {
    var size: (x: Int, y: Int)
    var location: (x: Int, y: Int)
        
    init(size: (x: Int, y: Int)) {
        self.size = size
        location = (Self.getRandom(size.x), Self.getRandom(size.y))
    }
    
    private static func getRandom (_ value:Int) -> Int {
        Int.random(in: 0...value-1)
    }
}

其他解决方案是将您的 location属性 定义为惰性的,然后 self 可访问并且该位置将仅执行一次并在代码中调用后执行.

struct CurrentData {
    var size: (x: Int, y: Int)
    lazy var location: (x: Int, y: Int) = {
        (getRandom(size.x), getRandom(size.y))
    }()
        
    init(size: (x: Int, y: Int)) {
        self.size = size
    }
    
    private func getRandom (_ value:Int) -> Int {
        Int.random(in: 0...value-1)
    }
}