ios - Cache static function result in Swift? -
i have static function generates uicolor
object can reused several times throughout application. don't want code run every time, first time , place cache, let subsequent retrieval grab cache. caveat value can change don't want permanently persist value, persist memory if app restarted, grab latest value , use throughout lifecycle.
here function looks like:
class appconfig: nsobject { static func getglobaltintcolor(alpha: float = 1) -> uicolor! { let colors = split(somevarfrominfoplist) { $0 == "," } let red = cgfloat(colors[0].toint() ?? 0) / cgfloat(255) let green = cgfloat(colors[1].toint() ?? 0) / cgfloat(255) let blue = cgfloat(colors[2].toint() ?? 0) / cgfloat(255) return uicolor(red: red, green: green, blue: blue, alpha: cgfloat(alpha)) } }
i don't want getglobaltintcolor
run logic every time. how cache first time , let served rest of app's lifecycle?
you describing static
variable rather function. give variable initializer function creates color.
class appconfig: nsobject { static var alpha : cgfloat = 1 static var globaltintcolor : uicolor = { // figure out color once, possibly based on `alpha` return thecolor }() }
this works because static var
initializer lazy; can depend on alpha
, not initialized until ask value first time. moreover, initializer function will not run again thereafter (unless quit , relaunch app), you're looking for.
Comments
Post a Comment