【问题标题】:float2 extension error, self used before stored properties initialised?float2 扩展错误,在存储属性初始化之前自行使用?
【发布时间】:2015-09-11 20:54:45
【问题描述】:

我回顾了我在Xcode 7.0 beta 3 (7A152u) 中所做的一个项目,我使用以下extensionCGPoint 初始化程序添加到float2(下面的代码与 WWDC2015 演示项目 DemoBots 中使用的代码相同) 早在 7 月下旬这工作正常,但现在使用 Xcode 7.0 GM (7A218) 我收到错误:

TEST.swift:32:11: 'self' used before all stored properties are initialized

我查看了各种发行说明,但找不到任何相关内容,谁能帮助我或指出正确的方向,说明为什么现在失败以及如何解决?

// Extend `float2` to add an initializer from a `CGPoint`.
extension float2 {
// MARK: Initialization

    /// Initialize with a `CGPoint` type.
    init(_ point: CGPoint) {
        x = Float(point.x) // << Above Error Here
        y = Float(point.y) // << Above Error Here
    }
}

【问题讨论】:

    标签: swift


    【解决方案1】:

    如果你使用,问题就解决了:

    init(_ point: CGPoint) {
        self = float2(x: Float(point.x), y: Float(point.y))
    }
    

    init(_ point: CGPoint) {
        self.init(x: Float(point.x), y: Float(point.y))
    }
    

    或者,正如 Martin R 所指出的:

    init(_ point: CGPoint) {
        self.init()
        x = Float(point.x)
        y = Float(point.y)
    }
    

    第二种方式用在latest DemoBots project中的float2扩展中。

    正如 Stephen Canon 在下面的评论中所说,这是因为:在 WWDC 种子中,simd 结构具有本机标量作为组件,因此以这种方式进行初始化是可行的。在后来的种子中,simd 结构由 LLVM 内置向量支持,组件 xy 等只是 { get set } 计算属性。

    【讨论】:

    • 了解为什么问题中的代码无法编译会很有趣。 CGPoint 的类似扩展而不是 float2 编译没有问题。
    • @MartinR:在 WWDC 种子中,simd 结构具有本地标量作为组件,因此以这种方式进行初始化是可行的。在后来的种子中,simd 结构由 LLVM 内置向量支持,组件 xy 等只是 { get set } 计算属性。
    • 我只是把它换成了self.goalAgent.position = float2(Float(position.x), Float(position.y)),但正如 Martin R 所说,我更好奇发生了什么变化,因为我也在使用 CGPoint 扩展,它编译得很好,并且在结构上几乎相同。跨度>
    • @StephenCanon:谢谢,这似乎可以解释。 – 在分配属性之前调用 self.init() 也可以。
    • @ABakerSmith:我建议您将解释添加到答案本身(并注明出处)。这将使答案自成一体,并且有时会删除 cmets。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 2016-04-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多