Coding for All
Lesson 3: Two Dogs
Two Dogs Build two independent values from one struct.
1struct Dog {
2 var name: String
3}
4
5let rex = Dog(name: "Rex")
6let bella = Dog(name: "Bella")
7print(rex.name)
8print(bella.name)
Terminal
$ swift main.swift
Rex
Bella
Every line, explained
struct Dog {
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".
var name: String
A variable inside a struct is called a property; every Dog gets its own.
}
This } closes the struct.
let rex = Dog(name: "Rex")
One struct definition...
let bella = Dog(name: "Bella")
...as many values as you like. Think of one house plan and a whole street of houses. bella's name is completely separate from rex's.
print(rex.name)
print(...) works exactly as in Intro to Swift.
print(bella.name)
print(...) works exactly as in Intro to Swift. Two values, two different names.