在惰性存储 属性 中使用函数时出现编译器错误

Compiler error when using function in lazy stored property

我在尝试 return 来自惰性存储 属性 中的函数的值时收到一条错误消息,提示 "Cannot convert value of type 'String' to argument type 'Test'"。我无法在惰性变量的闭包中发现任何问题。

import UIKit

public struct Value {}

public class Test {

    var id: String = ""

    public func getValueById(id: String) -> Value {
        return Value()
    }

    public lazy var value: Value = {
        // Compiler error: Cannot convert value of 'String' to expected argument type 'Test'
        return getValueById(self.id)
    }() 
}

编译器对 getValueById 感到困惑并且错误消息没有意义 - 如果没有误导的话。

你需要的是在闭包内的getValueById(self.id)前面加上self

public struct Value {}

public class Test {

    var id: String = ""

    public func getValueById(id: String) -> Value {
        return Value()
    }

    public lazy var value: Value = {
        return self.getValueById(self.id)
    }() 
}