Skip to content

Instantly share code, notes, and snippets.

View SebastianBoldt's full-sized avatar
:octocat:

Sebastian Boldt SebastianBoldt

:octocat:
View GitHub Profile
Task {
await MainActor.run {
// ....
}
}
// or
Task { @MainActor in
// .....
let viewState = await MainActor.run { () -> ViewState in
// ....
}
func loadData() async -> Data {
return Data()
}
func refreshUI(with data: Data) async {
let data = await loadData()
await MainActor.run {
view.update(with: data)
}
}
actor BankAccount {
private let accountHolder: String?
// .....
nonisolated func logAccountHolder() {
print(accountHolder ?? "No account holder")
}
}
Task {
let bankAccount = BankAccount(accountHolder: "Sebastian Boldt")
actor BankAccount {
var balance: Int = 0
let accountHolder: String?
init(accountHolder: String) {
self.accountHolder = accountHolder
}
func logBalance() {
print(balance) // Accessing Balance without await
actor BankAccount {
private var balance: Int = 0
let accountHolder: String? // 3.
init(accountHolder: String) {
self.accountHolder = accountHolder // 2.
}
func logBalance() {
print(balance) // Accessing Balance without await
actor BankAccount {}
enum TaskData {
@TaskLocal static var userId: Int?
}
Task {
await TaskData.$userId.withValue(786) {
let task = Task {
print(TaskData.userId ?? "No User Id")
}
print(TaskData.userId ?? "No User Id")
enum TaskData {
@TaskLocal static var userName: String?
}
let task = Task {
for i in 0..<1_000_000_000_000_000 {
try Task.checkCancellation()
print(i)
}
}
task.cancel()