Hello, I have following questions regarding best data structure, it’s use and some interesting compiler answers:
first my ideas: I want to have readable code and want to access my data by using a String as index / key-value instead of using an array with 2 elements forced using a numeric index. Eg.:
count[“home”].balls instead of count[0].balls or
count["guest].strikes instead of count[1].strikes
1.) definition of a class
class PitchCount: ObservableObject {
var balls: Int
var strikes: Int
var totalPitchCount: Int {
return balls + strikes
}
init(balls: Int, strikes: Int) {
self.balls = balls
self.strikes = strikes
}
}
2.) us of the class in a data model. I have deleted all the other properties due to better code reading
class TestModel: ObservableObject {
@Published var pitchCounts: [String: PitchCount] = ["guest": PitchCount(balls: 0, strikes: 0),
"home": PitchCount(balls: 0, strikes: 0)]
func changePitchCount(offensiveTeam: String, pitch: String) -> String{
if pitch == "ball" {
pitchCounts[offensiveTeam]!.balls += 1
} else {
pitchCounts[offensiveTeam]!.strikes += 1
}
}
Now my question. if I code pitchCounts[offensiveTeam].balls +=1 (no “!”), Xcode shows the following error message: “Value of optional type ‘Int?’ must be unwrapped to a value of type ‘Int’”. Force-unwrap using ‘!’ to abort execution if the optional value contains ‘nil’. Why? ‘balls’ is not declared as an optional.
What’s best practice for such a data use? Is Dictionary the right type for such an intended use?
Thanks and best regards
Peter