Skip to content

Commit 15f24c6

Browse files
CypherPoetCypherPoet
authored andcommitted
Day 8: Structs, Part One
1 parent 827b602 commit 15f24c6

File tree

5 files changed

+88
-0
lines changed

5 files changed

+88
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,4 @@ Feedback and suggestions are highly appreciated. I'll be opening up [issues](htt
2323
- [Day 5: Functions](/day-005)
2424
- [Day 6: Closures, Part 1](/day-006)
2525
- [Day 7: Closures, Part 2](/day-007)
26+
- [Day 8: Structs, Part One](/day-008)

day-008/README.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Day 8: Structs, Part One
2+
3+
_Follow along at https://www.hackingwithswift.com/100/8_
4+
5+
## 📒 Field Notes
6+
7+
### Structs are Value Types
8+
9+
Like classes and enums, structs are way to implement a custom type in Swift. Unlike classes, however, structs are passed around by copy (a new replication their value in memory) as opposed to by reference (a variable that links to the same value in memory).
10+
11+
This _can_ have important implications for performance (although Swift's "copy on write" behavior goes a long way to optimize things) — but it definitely has important implications for state mutation.
12+
13+
#### Classes vs Structs
14+
15+
There's no One Rule To Rule Them All in the matter of Class vs Struct, but the best summary I've found so far comes from [Ray Wenderlich's Swift Style Guide](https://github.com/raywenderlich/swift-style-guide#which-one-to-use), which suggests **preferring structs for object that don't have an intrinsic identity or a lifecycle**. A person would be a class; their birthdate would be a struct.
16+
17+
**📝Note:** I've only just begun to explore what appears to be a _very_ long-running debate/dilemma within the Swift Community. This [Stack Overflow thread](https://stackoverflow.com/questions/24232799/why-choose-struct-over-class) seems like a sufficiently deep rabbit hole, but right now, I'm going with Apple's [official docs](https://developer.apple.com/documentation/swift/choosing_between_structures_and_classes) while I try to acquire more knowledge, experience, and evidence going forward.
18+
19+
20+
### Mutating Member Functions
21+
22+
Structs ultimately serves as "templates" or "prototypes" for instances, meaning we might want some instances to be mutable and others to be constants. To help the compiler (and fellow readers) out with signalling our intent, we can add the `mutating` attribute to any method that wishes to do so.
23+
24+
```swift
25+
struct City {
26+
var name: String
27+
var population: Int
28+
29+
mutating func grantEntry() -> Void {
30+
population += 1
31+
}
32+
}
33+
```
34+
35+
This allows us to create a `City` variable, and call `grantEntry` on it. Correspondingly, if we create a `City` constant, calling `grantEntry` will throw an error at compile time 👍.
36+
37+
Rounding out the safety benefits of `mutating`, Xcode will also throw a helpful error message if we
38+
try to define a mutating function that _without_ the `mutating` keyword:
39+
40+
![](./images/bad-mutating-function.png)
41+
42+
43+
## 🔗 Related Links
44+
45+
- [Apple's Swift Documentation: Choosing Between Structures and Classes](https://developer.apple.com/documentation/swift/choosing_between_structures_and_classes)
42.4 KB
Loading
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import UIKit
2+
3+
struct City {
4+
var name: String
5+
var country: String
6+
var isCapital: Bool
7+
8+
var population: Int {
9+
didSet {
10+
print("New population of \(name): \(population)")
11+
}
12+
}
13+
14+
var capitalStatus: String {
15+
return "\(name) is \(isCapital ? "" : "not ")the capital of \(country)"
16+
}
17+
18+
func taxIncome() -> Double {
19+
return Double(population) * 0.0 // 😛
20+
}
21+
22+
mutating func grantEntry() -> Void {
23+
population += 1
24+
}
25+
}
26+
27+
28+
let paris = City(name: "Paris", country: "France", isCapital: true, population: 2_241_346)
29+
var nyc = City(name: "New York City", country: "The United States", isCapital: false, population: 8_550_405)
30+
31+
32+
print(paris.capitalStatus)
33+
print(nyc.capitalStatus)
34+
35+
nyc.population += 1
36+
nyc.grantEntry()
37+
38+
//paris.grantEntry() // Error: Cannot use mutating member on immutable value
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' executeOnSourceChanges='false'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

0 commit comments

Comments
 (0)