Line At A Time
Lesson 7: A Team of Structs
A Team of Structs Combine structs with arrays and loops.
1struct Player {
2 var name: String
3 var score: Int
4
5 func cheer() {
6 print("Go \(name)! Score: \(score)")
7 }
8}
9
10let ada = Player(name: "Ada", score: 100)
11let grace = Player(name: "Grace", score: 120)
12let players = [ada, grace]
13for player in players {
14 player.cheer()
15}
Terminal
$ swift main.swift
Go Ada! Score: 100
Go Grace! Score: 120
Every line, explained
struct Player {
struct Dog { ... } defines a struct: a blueprint bundling values that belong together. Swift developers reach for structs first when they want to model a "thing". This one is for game players.
var name: String
This player's name.
var score: Int
This player's score.
func cheer() {
Something every Player can do.
print("Go \(name)! Score: \(score)")
Uses both of this player's properties.
}
This } closes the method.
}
This } closes the struct.
let ada = Player(name: "Ada", score: 100)
One player...
let grace = Player(name: "Grace", score: 120)
...and another.
let players = [ada, grace]
Structs can go in an array, just like numbers or strings!
for player in players {
And for-in can visit each one: everything from Intro to Swift works with your own structs.
player.cheer()
Each player cheers with their own name and score. Structs, methods, arrays and loops: that is real Swift!
}
This } closes the for loop.