ios - How can I create a static computed property that computes only once? -
i've created computed static property i'd have computed once , whenever accessed after return original computed value. lazy
properties appear want after bit of searching appears static properties lazy
default.
when run following code comes out fine first time accessed/ if run each unit test individually. when access 2nd time i'm given empty array.
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] }()
code called 2nd time , returns empty array
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) }
your solution should work. maybe there wrong other part of code. take @ following example:
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)")
prints:
mystrings: ["a", "b"] static strings: ["a", "b"] mystrings: ["a", "b", "c"] static strings: ["a", "b"]
so following piece of code should work:
class conferencenumberdirectory { static let att: [conferencenumber] = { return builddirectory(for: .att, from: jsonarray) }() }
Comments
Post a Comment