Reputation: 1192
I've tried following this and this and this, but I'm having issues getting the data from a string array.
I have my state set as
businessHours = : [
"Monday: 7:00 AM – 7:00 PM",
"Tuesday: 7:00 AM – 7:00 PM",
"Wednesday: 7:00 AM – 7:00 PM",
"Thursday: 7:00 AM – 7:00 PM",
"Friday: 7:00 AM – 7:00 PM",
"Saturday: 7:00 AM – 7:00 PM",
"Sunday: Closed"
]
This only gets me the first element from the array
ForEach(businessHours.indices) {
Text(self.businessHours[$0])
}
This fails
ForEach(businessHours.indices) {
Text(self.businessHours)
}
This works in the console
for businesshour in businessHours {
print("Hours: \(businesshour).")
}
What am I doing wrong here?
Upvotes: 2
Views: 3510
Reputation: 1101
There is a much simpler way..
When you have an array where the values are separated by ", " you can divide the array with this comma symbol
For Example: I have a user model with food. Food is an array, which looks similar like this:
user.food = ["Banana", "Strawberry", "Apple"]
You noticed: Every item is separated by the comma.
Now you can simply use
Text(user.food.joined(separator: ", "))
.multilineTextAlignment(.trailing)
.padding()
Et voilá :)
Upvotes: 3
Reputation: 1192
I figured it out.
(0..<businessHours.count, id: \.self) { index in
Text(self.businessHours[index])
}
Upvotes: 0
Reputation: 257711
Here is a demo that works. Tested with Xcode 12 / iOS 14
struct DemoView: View {
let businessHours = [
"Monday: 7:00 AM – 7:00 PM",
"Tuesday: 7:00 AM – 7:00 PM",
"Wednesday: 7:00 AM – 7:00 PM",
"Thursday: 7:00 AM – 7:00 PM",
"Friday: 7:00 AM – 7:00 PM",
"Saturday: 7:00 AM – 7:00 PM",
"Sunday: Closed"
]
var body: some View {
VStack {
ForEach(businessHours.indices) {
Text(self.businessHours[$0])
}
}
}
}
Upvotes: 1