View.onChange(of:) cannot accept an Optional argument
Open
Nobody has claimed this yet.
- Dominant language
- Swift
- Stars
- 330
- Forks
- 76
- Avg merge
- 3h 6m
- Merged PRs (30d)
- 1
Description
Calling onChange(of: T, perform: { oldValue, newValue }) only works for non-optional Equatable values.
One workaround is to fall back to a sentinel value when checking, as so:
struct MyView {
@State var someState: String = "ABC"
@State var someOptionalState: String? = nil
var body: some View {
Text("ABC")
// this works fine
.onChange(of: someState) { oldValue, newValue in … }
#if !SKIP
// this fails to compile in Skip
.onChange(of: someOptionalState) { oldValue, newValue in … }
#else
// this is the workaround for Skip
.onChange(of: someOptionalState ?? "SOME_SENTINEL") { oldValue, newValue in … }
#endif
}
}
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the optional-value failure described for View.onChange(of:), comparing it with the working non-optional call and the sentinel workaround. The change is complete when an Optional Equatable argument compiles and its old and new values are available to the callback without requiring a sentinel.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- swift
- Domain
- mobile-dev
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100