Skip to content

Instantly share code, notes, and snippets.

View SebastianBoldt's full-sized avatar
:octocat:

Sebastian Boldt SebastianBoldt

:octocat:
View GitHub Profile
extension ViewController {
func addItems(items: [Item], to section: Section) {
var snapshot = dataSource.snapshot()
snapshot.appendSections([section])
snapshot.appendItems(items, toSection: section)
dataSource.apply(snapshot)
}
}
import UIKit
enum Section {
case section1
case section2
}
struct Item: Hashable {
let color: UIColor
}
@SebastianBoldt
SebastianBoldt / AsyncAwait.swift
Last active February 3, 2022 08:36
AsyncAwait.swift
struct SomeView {
var data: Data? {
get async throws {
return await fetchData()
}
}
func fetchData() async throws -> Data? {
// ....
}
func getUserData(for id: Int) async throws -> Family {
let user = try await getUser(id: id)
let parents = try await getParents(of: user)
return createFamily(user, parent)
}
@main
struct MainApp {
static func main() async {
await asyncFunction()
}
}
struct ContentView: View {
@State var taskTrigger: Bool = false
var body: some View {
Button("Execute Task", action: {
taskTrigger.toggle()
}).task(id: taskTrigger) {
do {
let newText = try await getText()
print(newText)
} catch {
struct ContentView: View {
var body: some View {
VStack {
Button("Async") {
Task {
await asyncFunction()
}
}
}
}
func getStatistics(for user: User) async throws -> (Statistics, Statistics) {
async let old = getOldUserStatistics(of: user)
async let new = getNewUserStatistics(of: user)
let awaitedOldStats = await old
let awaitedNewStats = await new
return (awaitedOldStats, awaitedNewStats)
}
enum SomeError: Error {
case foo
}
func completionFunction(completion: @escaping ([Data], error: @escaping (Error) -> Void) -> Void) {
getData(complete: completion)
}
func asyncFunctionWrapper() async -> Data {
await withCheckedThrowingContinuation { continuation in
class DelegateWrapper: NSObject, ObservableObject, CLLocationManagerDelegate {
private var continuation: CheckedContinuation<Data?, Error>?
private let dataService = SomeClassThatReturnsData()
override init() {
super.init()
dataService.delegate = self
}
func requestData() async throws -> Data? {