如何创建仅计算一次的静态计算属性?

时间:2017-08-18 12:56:59

标签: ios swift

我已经创建了一个计算的静态属性,我想让它计算一次,然后每次访问时都会返回原始的计算值。 lazy属性似乎是我想要的,但经过一些搜索后,默认显示静态属性为lazy

当我运行以下代码时,第一次访问/如果我单独运行每个单元测试时它会很好。但是当我第二次访问它时,我得到一个空数组。

static var att: [ConferenceNumber] = {
    let list = buildDirectory(for: .att, from: jsonArray)
    return list
}()

private static let jsonArray: [Any]? = {
    let numbersFilePath = Bundle.main.path(forResource: "numbers", ofType:"json")
    let data = try! Data(contentsOf: URL(fileURLWithPath:numbersFilePath!), options: .uncached)

    return try! JSONSerialization.jsonObject(with: data) as? [Any]
}()

第二次调用此代码并返回空数组的代码

private static func isAttMeeting(meetingText: String, parsedPhoneNumbers: [String]) -> Bool {
    let attPhoneNumbers = ConferenceNumberDirectory.att.map{$0.number}
    let attNumberWasParsed = parsedPhoneNumbers.intersects(with: attPhoneNumbers)
    if attNumberWasParsed {
        return true
    }
    return meetingText.contains(pattern: attURLRegex) || meetingText.contains(pattern: attURLRegex2)
}

2 个答案:

答案 0 :(得分:2)

您的解决方案应该有效。也许你的代码的其他部分有问题。看一下下面的例子:

var myStrings = ["a", "b"]

class SomeClass {
    static let strings: [String] = {
        return myStrings
    }()
}

print("myStrings: \(myStrings)")
print("static strings: \(SomeClass.strings)")

myStrings.append("c")

print("myStrings: \(myStrings)")
print("static strings: \(SomeClass.strings)")

打印:

myStrings: ["a", "b"]
static strings: ["a", "b"]
myStrings: ["a", "b", "c"]
static strings: ["a", "b"]

所以对你来说,以下代码应该可以工作:

class ConferenceNumberDirectory {
    static let att: [ConferenceNumber] = {
        return buildDirectory(for: .att, from: jsonArray)
    }()
}

答案 1 :(得分:-1)

看起来这是我在另一个测试中遇到问题的原因。我需要在单元测试中停止使用静态属性。

    override func tearDown() {
    ConferenceNumberDirectory.att = []
    ConferenceNumberDirectory.arkadin = []
    ConferenceNumberDirectory.webex = []
    ConferenceNumberDirectory.zoom = []
    super.tearDown()