-
Notifications
You must be signed in to change notification settings - Fork 0
/
60_EquatableExample.swift
111 lines (92 loc) · 3.2 KB
/
60_EquatableExample.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import SwiftUI
extension Int {
/// Является ли число нечётным
var isOdd: Bool { self % 2 != 0 }
}
enum EquatableExample {
struct ContentView: View {
@State private var n = 3
var body: some View {
VStack(spacing: 20) {
BrokenView1(number: n)
BrokenView2(number: n, isOdd: n.isOdd)
HardView(number: n, isOdd: n.isOdd)
EasyFinalView(isOdd: n.isOdd)
Button("Сгенерировать число") {
n = Int.random(in: 1...1000)
}
Text("\(n)")
}
}
}
struct BrokenView1: View, Equatable {
let number: Int
var body: some View {
print("Вычисляем body 1, isOdd = \(number.isOdd)")
return ExampleTextView(
text: number.isOdd ? "Нечётный" : "Чётный",
backgroundColor: number.isOdd ? Color.red : Color.green
)
}
static func == (lhs: BrokenView1, rhs: BrokenView1) -> Bool {
lhs.number.isOdd == rhs.number.isOdd
}
}
struct BrokenView2: View, Equatable {
let number: Int
let isOdd: Bool
var body: some View {
print("Вычисляем body 2, isOdd = \(isOdd)")
return ExampleTextView(
text: isOdd ? "Нечётный" : "Чётный",
backgroundColor: isOdd ? Color.red : Color.green
)
}
static func == (lhs: BrokenView2, rhs: BrokenView2) -> Bool {
lhs.number.isOdd == rhs.number.isOdd
}
}
struct HardView: View, Equatable {
let number: Int
let isOdd: Bool
@State private var test = true
var body: some View {
print("Вычисляем body 3, isOdd = \(isOdd)")
return ExampleTextView(
text: isOdd ? "Нечётный" : "Чётный",
backgroundColor: isOdd ? Color.red : Color.green
)
.rotationEffect(.degrees(test ? 0 : 360))
}
static func == (lhs: HardView, rhs: HardView) -> Bool {
lhs.number.isOdd == rhs.number.isOdd
// lhs.isOdd == rhs.isOdd // <- тоже рабочий вариант
}
}
struct EasyFinalView: View {
let isOdd: Bool
var body: some View {
print("Вычисляем body 4, isOdd = \(isOdd)")
return ExampleTextView(
text: isOdd ? "Нечётный" : "Чётный",
backgroundColor: isOdd ? Color.red : Color.green
)
}
}
struct ExampleTextView: View {
let text: String
let backgroundColor: Color
var body: some View {
Text(text)
.foregroundStyle(.white)
.padding(20)
.background(
RoundedRectangle(cornerRadius: 10)
.fill(backgroundColor)
)
}
}
}
#Preview {
EquatableExample.ContentView()
}