Set Encodable value for key in Firebase database (async/await)

Swift, Async/await, Firebase

Set an Encodable value for a key in Firebase database using Swift's async/await

swift

import FirebaseDatabase import FirebaseDatabaseSwift public extension DatabaseReference { @discardableResult func setValue( from value: some Encodable, encoder: Database.Encoder = Database.Encoder() ) async throws -> DatabaseReference { let encoded = try encoder.encode(value) return try await withCheckedThrowingContinuation { continuation in setValue(encoded) { error, ref in if let error { continuation.resume(throwing: error) } else { continuation.resume(returning: ref) } } } } }

How to use?

do { let ref = Database.database().reference().child("foo") try await ref.setValue(from: "bar" /* Any encodable object */) print("Value set") } catch { print("Setting value failed with error: \(error)") }