I am wondering if the following use of Enum, static var, computed property and whatnot are good practices to manage states in Swift and SwiftUI.
I'm learning Swift by myself and don't have anyone to review my code or senior to learn from.
enum ARSessionState {
case selfie
case world
mutating func toggle() {
self = (self == .selfie) ? .world : .selfie
}
private static var selfieConfiguration: ARFaceTrackingConfiguration = {
let configuration = ARFaceTrackingConfiguration()
configuration.isWorldTrackingEnabled = true
return configuration
}()
private static var worldConfiguration: ARWorldTrackingConfiguration = {
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = [.horizontal]
configuration.userFaceTrackingEnabled = true
return configuration
}()
var configuration: ARConfiguration {
switch self {
case .selfie:
return ARSessionState.selfieConfiguration
case .world:
return ARSessionState.worldConfiguration
}
}
}
and I use this in a SwiftUI view like this:
struct ContentView : View {
@State private var session: ARSessionState = .world
...
var body: some View {
ZStack {
...
Button(action: {session.toggle()} ) {
Image(systemName: "arrow.triangle.2.circlepath.camera")
.resizable()
.scaledToFit()
.frame(width: 50, height: 50)
}.onChange(of: session) { newValue in
let configuration = session.configuration
...
}
}
}
}
Rather than using a simple Bool, I wanted to define two states and toggle between them from a Button action because selfie/world made more sense conceptually than true/false. So I defined ARSessionState and added two cases selfie and world.
Now, when the user changes the state, I wanted to have different ARConfigurations to kick-in based on the changed state, namely ARWorldTrackingConfiguration and ARFaceTrackingConfiguration. So inside .onchange {...} I call session.configuration, which should give me corresponding ARConfiguration based on the session's state.
So my questions are, is it a good practice to
define an Enum with two cases like this to replace true/false Bool?
define a mutating func to change the state? I'm not confident how state change will play out in SwiftUI. Specifically with @State property-wrapper.
define private static var properties within Enum? I did this because I could not have stored properties in Enum.
call the static properties from a computed property? (in this case, var configuration: ARConfiguration)
Any other comments related to good Swift programming practices are greatly appreciated too!