sindresorhus / sindresorhus/Defaults
Handle animations in SwiftUI with @Default
Nobody has claimed this yet.
- Dominant language
- Swift
- Stars
- 2.5k
- Forks
- 163
- PR merge metrics
- No merged PRs in 30d
Description
Hi! First of all, I'm sorry if it's a stupid question or if it has nothing to do with these package.
I'm trying to animate a List where the order of elements depends on a variable in Defaults.
If I'm using a @State, it's working as expected.
If I'm using a @Default, animation doesn't work.
These works:
enum OrderBy: String, Codable, Defaults.Serializable {
case index, name
}
struct Element: Identifiable {
let id: String
let index: Int
let name: String
}
let allElements: [Element] = [
.init(id: "1", index: 5, name: "Element 1"),
.init(id: "2", index: 4, name: "Element 2"),
.init(id: "3", index: 1, name: "Element 3"),
.init(id: "4", index: 3, name: "Element 4"),
.init(id: "5", index: 2, name: "Element 5"),
]
struct MyView: View {
@State var order: OrderBy = .index
func toggleOrder() {
withAnimation {
order = order == .index ? .name : .index
}
}
var elements: [Element] {
allElements.sorted(by: { order == .index ? $0.index < $1.index : $0.name < $1.name })
}
var body: some View {
Picker("Order by", selection: $order) {
Text("index").tag(OrderBy.index)
Text("name").tag(OrderBy.name)
}
List {
ForEach(elements, id: \.id) { element in
Text("Element \(element.name)")
}
}
}
}
These doesn't work:
extension Defaults.Keys {
static let order = Key<OrderBy>("orderBy", default: OrderBy.index)
}
struct MyView: View {
@Default(.order) var order
func toggleOrder() {
withAnimation {
listSortOption = listSortOption == .index ? .name : .index
}
}
...
}
Is these a limitation of the package or is it completely something else?
Thanks
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 with the provided SwiftUI List reproduction and compare the @State and @Default cases, focusing on the @Default property wrapper's observation and update behavior. Confirm whether withAnimation receives the change, then determine whether the package can support the same animation behavior; done means the cause is established and the reproduction works as expected if a fix is possible.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- swift
- Domain
- mobile-dev
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100