         return defaults
     }
     
-    private init(db: UserDefaultsBackEnd) {
+    private init(db: Database) {
         self.db = db
     }
     

// To run this playground, select and build the GRDBOSX scheme.

import GRDB

// UserDefaults can work with both DatabaseQueue and DatabasePool
public protocol UserDefaultsBackEnd: class, DatabaseReader, DatabaseWriter { }
extension DatabaseQueue : UserDefaultsBackEnd { }
extension DatabasePool : UserDefaultsBackEnd { }
extension Database : UserDefaultsBackEnd { }

/// UserDefaults is a class that behaves like NSUserDefaults.
///
/// Usage:
///
///     let dbQueue = DatabaseQueue(...)
///     let defaults = UserDefaults.inDatabase(db)
///
///     defaults.integerForKey("bar") // 0
///     defaults.setInteger(12, forKey: "bar")
///     defaults.integerForKey("bar") // 12
///
///     dbQueue.inDatabase { db in
///         let defaults = UserDefaults.inDatabase(db)
///         defaults.integerForKey("bar") // 12
///     }
public class UserDefaults {
    private weak var db: UserDefaultsBackEnd!
    private var needsTable: Bool = true
    private static var registeredDefaults: [UserDefaults] = []
    
    /// Returns the defaults for the database
    public static func inDatabase(db: UserDefaultsBackEnd) -> UserDefaults {
        registeredDefaults = registeredDefaults.filter { $0.db != nil }
        for defaults in registeredDefaults where defaults.db === db { return defaults }
        let defaults = UserDefaults(db: db)

// ============================================================

let dbQueue = DatabaseQueue()
dbQueue.inDatabase { db in
    let defaults = UserDefaults.inDatabase(db)
    
    defaults.integerForKey("bar") // 0
    defaults.setInteger(12, forKey: "bar")
    defaults.integerForKey("bar") // 12
}
