Protocols
Protocols
PROTOCOLS - 02
Swift Protocols for Reactive UI, Layout, and Concurrency
Explanation:
Use Case:
Required for data passed between structured concurrency units like tasks and
actors.
ViewBuilder
Explanation:
Example:
@ViewBuilder
func buildSection(show: Bool) -> some View {
if show {
Text("Visible")
} else {
EmptyView()
}
}
Use Case:
Explanation:
A reference type that protects its mutable state using isolation from concurrency issues.
Protects from data races by allowing only one task at a time to access its internal properties.
Example:
actor Counter {
private var count = 0
func increment() {
count += 1
}
}
Use Case:
Explanation:
Example:
@MainActor
class ViewModel {
var title: String = ""
func updateUI() {
// always runs on main thread
}
}
Use Case:
Explanation:
Example:
Use Case:
Used by:
AsyncSequence.makeAsyncIterator()
→ returns this type to power the loop
AsyncSequence
Explanation:
A protocol for types that emit values over time, used with for await.
Example:
struct Counter: AsyncSequence { Use Case:
typealias Element = Int
Consume values from
streams like timers,
func makeAsyncIterator() -> Iterator {
APIs, or custom async
Iterator()
collections. Think of it
}
as : for-in, but with
struct Iterator: AsyncIteratorProtocol {
pauses — works over
var current = 0
time
mutating func next() async -> Int? {
current < 3 ? current : nil
}
}
} // Usage:
for await value in Counter() {
print(value) // 0, 1, 2
}
ResultBuilder
Explanation:
Power behind SwiftUI DSL — lets you build structured data using code blocks.
Example:
@resultBuilder Use Case:
struct StringBuilder {
Create custom
static func buildBlock(_ components: String...) -> String {
builders like SwiftUI’s
components.joined(separator: " ")
ViewBuilder.
}
}
Explanation:
Example:
Use Case:
Explanation:
}
do {
try login()
} catch {
Use Case:
Explanation:
Example:
Use Case:
}
Thanks for Reading !
Lets Connect:
Sri Hari YS
iOS Lead Developer | Swift & SwiftUI Specialist
[email protected]
github
github