Last active
June 8, 2023 18:50
-
-
Save siracusa/fa2457bbfef11658751cab6a6c19cc6f to your computer and use it in GitHub Desktop.
Possible workarounds for lazy properties in an @observable class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
import Observation | |
@Observable | |
class User { | |
@ObservationIgnored lazy var id : Int = { | |
return Int.random(in: 1...100) | |
}() | |
} | |
// | |
// …or… | |
// | |
@Observable | |
public class User { | |
var idStorage : Int? = nil | |
var id : Int { | |
get { | |
if idStorage == nil { | |
idStorage = Int.random(in: 1...100) | |
} | |
return idStorage! | |
} | |
set { | |
idStorage = newValue | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment