I’m currently developing an app in SwiftUI for the first time and I’ve run into an issue I don’t quite understand.
What I’m ultimately trying to achieve is to fetch data from a backend API I’ve already built and to display that in a sort of "calendar" view inside the app. I’m trying to list all the events of the day on the screen with a DatePicker at the very top to choose the the date. I’ve built this up with a dummy dictionary of data to first try to get the looks of it right.
import SwiftUI
struct EventDot: View {
let minute: Int
var body: some View {
let position = CGFloat(minute) / 60.0
if position < 1 {
Circle()
.foregroundColor(.blue)
.frame(width: 13, height: 13)
.offset(x: position * UIScreen.main.bounds.width)
.onTapGesture {
print("Tapped at minute \(minute)")
}
} else {
EmptyView()
}
}
}
struct PlanView: View {
let minutesArray: [Int: Int] = [0: 15, 15: 1, 12: 36, 7: 55]
@State var selectedDate = Date.now
@State var events: [Int: String] = [:]
var body: some View {
VStack {
Text(selectedDate, style: .date)
DatePicker("Datum", selection: $selectedDate, displayedComponents: [.date]).bold()
Divider()
ScrollView {
VStack(spacing: 0) {
ForEach(0..<24, id: \.self) { hour in
Text("\(hour):00")
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.leading, 10)
.padding(.top, 40)
.font(.headline)
ForEach(events.filter { $0.key == hour }, id: \.self) { key, value in
}
if let minute = minutesArray[hour] {
EventDot(minute: minute)
.padding(.horizontal, 0)
.frame(maxWidth: .infinity)
}
Divider()
.background(.black)
.padding(.horizontal, 10)
}
}
}
}
.padding()
.onAppear {
events = minutesArray.reduce(into: [:]) { result, pair in
let (hour, minute) = pair
result[hour] = "Event at \(hour):\(minute)"
}
print(events)
}
}
}
#Preview {
PlanView()
}
This code works fine, except that whenever I try to filter/iterate over the events of a specific hour, Xcode shows me this:
Failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs)
Either I’ve found a bug in Swift or I’m missing something that Xcode is only displaying in a cryptic message.
>Solution :
The error is because of your ForEach(events.filter.... No need to file a bug.
Try using something like this instead:
ForEach(Array(events.filter { $0.key == hour }.enumerated()), id: \.offset) { key, element in
HStack {
Text("key: \(key) ")
Text("value: \(element.value) ")
}
}