Consider this stripped-down example of a view with a view model:
import Observation
import SwiftUI
struct MainView: View {
@State private var viewModel = ViewModel()
private let items = [0, 1, 2]
var body: some View {
List {
GroupedItemsView(
viewModel : viewModel.groupState,
groupedItems : [(0, items)]
)
}
}
}
fileprivate struct GroupedItemsView<ViewModel: GroupsExpandable>: View {
let viewModel : ViewModel
let groupedItems : [(ViewModel.GroupTag, [Int])]
var body: some View {
ForEach(groupedItems, id: \.0) { groupTag, items in
Text("nothing")
}
}
}
fileprivate protocol GroupsExpandable: AnyObject { // HERE
associatedtype GroupTag: Hashable
}
fileprivate final class GroupState<GroupTag: Hashable>: GroupsExpandable {}
@Observable
fileprivate final class ViewModel {
var groupState = GroupState<Int>()
}
#Preview {
MainView()
}
This compiles and runs fine in the Simulator, but it crashes in the Preview.
However, when I remove the fileprivate
modifier before GroupsExpandable
(see HERE), it also runs in the Preview.
What is the reason for this? Bug in Preview? Error on my side somewhere?
Thanks.
System is Xcode Version 16.3 (16E140) on a MacBook Pro 2018 (Intel) running Sequoia 15.3.2 Devices are iPhone 16 Pro Max with iOS 18.3.1, compiler is set to Swift 6.