【问题标题】:'self' used before all stored properties are initialized in struct在结构中初始化所有存储属性之前使用“自我”
【发布时间】:2020-10-05 11:26:13
【问题描述】:

我希望 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'”。怎么解决?

【问题讨论】:

标签: swift struct initialization


【解决方案1】:

getRandom 是一个实例方法,因此在self 上调用它(不过,Swift 允许您在访问实例方法/属性时省略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)
    }
}

【讨论】:

    【解决方案2】:

    而不是将您的 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)
        }
    }
    

    其他解决方案是将您的locationproperty 定义为惰性属性,然后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)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 2020-11-23
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      相关资源
      最近更新 更多