01. Cases of Structures

It will take about 2 minutes to finish reading this article.

1. Use structures when you’re modeling data.

Use structures when you’re modeling data that contains information about an entity with an identity that you don’t control. For example:

1
2
3
4
5
6
struct PenPalRecord {
let myID: Int
var myNickname: String
var recommendedPenPalID: Int
}
var myRecord = try JSONDecoder().decode(PenPalRecord.self, from: jsonResponse)

2. Use Structures and Protocols to Model Inheritance and Share Behavior.

Structures and classes both support a form of inheritance. Structures and protocols can only adopt protocols; they can’t inherit from classes. However, the kinds of inheritance hierarchies you can build with class inheritance can be also modeled using protocol inheritance and structures.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protocol AnimalCommonProtocol {
var name: String? { get set }
var weight: Double { get set }
func run()
}

struct Cat : AnimalCommonProtocol {
func run() {
print("cat run")
}
var name: String?
var weight: Double
var gender: String?
}

struct Dog : AnimalCommonProtocol {
func run() {
print("dog run")
}
var name: String?
var weight: Double
var type: String?
}