Reputation: 3
I recently started developing in xCode 8, with little experience.
In my application, the user gets to send three numbers to an 'score' array. After three numbers have been stored in array n1, I want the following three scores to be saved in array n2 and so on.
Currently, my code looks as following.
var shots = [Int]()
@IBAction func SaveScores(_ sender: UIButton) {
let first:Int? = Int(firstScore.text!)
let second:Int? = Int(secondScore.text!)
let third:Int? = Int(thirdScore.text!)
shots.append(first!)
shots.append(second!)
shots.append(third!)
firstScore.text = ""
secondScore.text = ""
thirdScore.text = ""
I am struggling to initialise a new array, after the first array holds three elements.
Any ideas anyone? Thanks! Daan
Upvotes: 0
Views: 46
Reputation: 1976
Do you want to keep the old shots
arrays? If not, you should be able to just overwrite the existing array:
shots = []
Otherwise you will need to store the shots
arrays in another array:
var shots: [[Int]] = []
@IBAction func SaveScores(_ sender: UIButton) {
let first:Int? = Int(firstScore.text!)
let second:Int? = Int(secondScore.text!)
let third:Int? = Int(thirdScore.text!)
let scores = [first!, second!, third!]
shots.append(scores)
firstScore.text = ""
secondScore.text = ""
thirdScore.text = ""
Here is the same code with more robust handling of optionals. The nil-coalescing operator ??
takes the optional value on the left-hand side if available, otherwise the default value on the right-hand side:
var shots: [[Int]] = []
@IBAction func SaveScores(_ sender: UIButton) {
guard let first = Int(firstScore.text ?? ""),
let second = Int(secondScore.text ?? ""),
let third = Int(thirdScore.text ?? "")
else {
// error handling
return
}
let scores = [first, second, third]
shots.append(scores)
firstScore.text = ""
secondScore.text = ""
thirdScore.text = ""
Upvotes: 1