Daily iOS
SwiftUI

Finding SwiftUI defects

This is a SwiftUI live coding review. Find as many defects as you can in the feed screen code below, and for each one say why it's a problem and how you'd fix it.

struct FeedView: View {
    @ObservedObject var vm = FeedViewModel()
    @State var items: [Post] = []
    var body: some View {
        List {
            ForEach(0..<items.count) { i in
                PostRow(post: items[i])
                    .onAppear { if i == items.count - 1 { Task { await vm.loadMore() } } }
            }
        }
        .onAppear { Task { items = await vm.fetch() } }
    }
}
How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

(1) The view creates the object under @ObservedObject, so it resets on every re-evaluation; use @State plus @Observable. (2) ForEach(0..<count) is a static range, so count changes crash or don't update; use an Identifiable ForEach. (3) State is stored twice, in vm and in @State. (4) The unstructured Task in onAppear isn't canceled; use .task. (5) Last-cell onAppear paging has no duplicate call guard.

Share a question