I am trying to get the "roles" to display as the text in a Picker. When I just use a generic Text view inside the Picker it will display 5 times like it is supposed to, but I can't seem to pull the name from the struct.
JSON Data:
[
{"roles": "Gorilla",
"index": 0},
{"roles": "Armadillo",
"index": 1},
{"roles": "Cheetah",
"index": 2},
{"roles": "Iguana",
"index": 3},
{"roles": "Monkey",
"index": 4}
]
Model:
import Foundation
struct inviteModel: Codable, Identifiable{
let id = UUID()
var roles:String
var index:Int
}
View:
@State var roleList = [inviteModel]()
private func loadRoles(){
Task {
var ackval = "58ikf0"
var request = URLRequest(url: URL(string: "MYURL")!)
request.httpMethod = "POST"
let parameters = "ack=\(ackVal)"
request.httpBody = parameters.data(using: .utf8)
let (data, response) = try await URLSession.shared.data(for: request as URLRequest)
if (response as? HTTPURLResponse)?.statusCode == 200 {
do{
self.roleList = try JSONDecoder().decode([inviteModel].self, from: data)
}catch{
print(error)
}
} else {
print("API Error")
}
isSending = false
}
}
Picker(selection: $role1, label: Text("Role 1")) {
ForEach(0..<roleList.count, id: \.self) { rlist in
Text(rlist.roles).tag(0)
}
}
Im sure its probably something simple but I am new to Swift.
UPDATE: I found the answer by looking at the code above that was provided.
The issue was, I was trying to give the ForEach loop a range instead of using the built in Swift features to iterate through the Data Model.
Picker(selection: $role1, label: Text("Role 1")) {
ForEach(roleList) { role in
Text("\(role.roles)").tag(role.index)
}
}