Skip to content
This repository has been archived by the owner on Oct 17, 2024. It is now read-only.

Commit

Permalink
Move from onSet using state to computed property
Browse files Browse the repository at this point in the history
  • Loading branch information
david-swift committed Jun 17, 2024
1 parent ab831c7 commit 1fc0647
Showing 1 changed file with 9 additions and 25 deletions.
34 changes: 9 additions & 25 deletions Tests/BindingReactorDemo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,33 +69,25 @@ struct BindingReactorDemo: View {
struct WindowContent: View {

@State private var password = ""
@State var checkStatus = PasswordChecker.allCases.enumerated().reduce([String: Bool]()) { dict, checker in
var dict = dict
dict[checker.element.rawValue] = false
return dict
var checkStatus: [String: Bool] {
PasswordChecker.allCases.enumerated().reduce([String: Bool]()) { dict, checker in
var dict = dict
dict[checker.element.rawValue] = check(password: password, checker: checker.element).1
return dict
}
}

var view: Body {
VStack {
FormSection("Password Checker") {
Form {
EntryRow("Password", text: $password.onSet { _ in
Task {
let results = await checkPassword(content: password)

Idle {
for result in results {
checkStatus[result.0] = result.1
}
}
}
})
EntryRow("Password", text: $password)
}
}
.padding()
ForEach(PasswordChecker.allCases) { checker in
CheckerButton(
isValid: binding(for: checker.rawValue),
isValid: .constant(checkStatus[checker.rawValue] ?? false),
checkerName: checker.label,
checkerInfo: checker.description
)
Expand All @@ -109,14 +101,6 @@ struct BindingReactorDemo: View {
}
}

private func binding(for key: String) -> Binding<Bool> {
.init {
checkStatus[key] ?? false
} set: { newValue in
checkStatus[key] = newValue
}
}

private func checkPassword(content password: String) async -> [(String, Bool)] {
var results: [(String, Bool)] = []

Expand All @@ -135,7 +119,7 @@ struct BindingReactorDemo: View {
return results
}

private func check(password: String, checker: PasswordChecker) async -> (String, Bool) {
private func check(password: String, checker: PasswordChecker) -> (String, Bool) {
switch checker {
case .length:
return (PasswordChecker.length.rawValue, password.count > 8)
Expand Down

0 comments on commit 1fc0647

Please sign in to comment.