Coding for All
Lesson 4: Methods
Methods Teach the struct a trick.
1struct Dog {
2 var name: String
3
4 func bark() {
5 print("\(name) says woof!")
6 }
7}
8
9let rex = Dog(name: "Rex")
10rex.bark()
Terminal
$ swift main.swift
Rex says woof!
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.
func bark() {
A func inside a struct is a method: something every Dog can do.
print("\(name) says woof!")
Inside a method you can use the properties directly: name here means "MY name, the name of whichever dog is barking".
}
This } closes the method.
}
This } closes the struct.
let rex = Dog(name: "Rex")
Swift writes the builder for you! Because Dog lists its properties, Swift automatically lets you build one with labels: Dog(name: "Rex"). (Other languages make you write this "constructor" yourself.)
rex.bark()
The dot calls the method: rex.bark() means "rex, bark!", and it prints rex's own name.