I am writing an app to track the distances that golf clubs hit a ball. I have a little experience in Python but I am very beginner with Swift and SwiftUI.
I have a .Swift file that contains the array I want to use to store my data.
import SwiftUI
import Combine
struct Club: Identifiable {
let id = UUID()
let clubName: String
let yards: Int
let strokesCounted: Int
}
struct ClubList {
static var inTheBag = [
Club(clubName: "Driver", yards: 250, strokesCounted: 0),
Club(clubName: "Putter", yards: 10, strokesCounted: 0),
Club(clubName: "3 Hybrid", yards: 180, strokesCounted: 0)
]
}
I am working on a view now that will take an input from the user and add the input to this array as “clubName: user input, yards: 0, strokesCounted: 0” and display the array as a list under the text entry box. I was able to do this when I was using a list only containing the names of the clubs a strings, but now that I have added the additional properties it doesn’t work anymore.
import SwiftUI
struct AddAClub: View {
@State private var usedWords = [String] ()
@State private var newClub: String = ""
var body: some View {
List {
Section{
TextField("Which club would you like to add?", text: $newClub)
.onSubmit(addNewClub)
}
Section {
ForEach(ClubList.inTheBag.Club.clubName) {
word in Text(word)
//>”Value of Type ‘[Club]’ has no member ‘Club’”
}
}
}
}; func addNewClub() {
let answer = newClub.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
guard answer.count > 0 else {return}
withAnimation {
let newClubFull = [Club(clubName: answer, yards: 0, strokesCounted: 0)]
ClubList.inTheBag.append(contentsOf: newClubFull)
}
newClub = ""
}
}
I have tried various changes to the argument for ForEach in the second section of the View. For example: inTheBag.Club.clubName, ClubList.inTheBag.clubname, Club, clubName, etc.
I would like to take the user input and add it to the array as a new Club with yards: 0 and strokesCounted: 0 (this may be working as the func addNewClub() shows no errors). I would also like to display the list of clubNames below the text entry as it updates.
@vadian answered my question in a comment.
ForEach(ClubList.inTheBag, id: \.clubName) { club in Text(club.clubName) }
Unrelated but consider to rename clubName
as name, club is redundant.