LoginSignup
3
2

More than 5 years have passed since last update.

[Swift] firebase ってこうやったら気持ちいいのでは?

Last updated at Posted at 2018-07-05

ついさっき触り始めたばかりだけど、observeがごちゃごちゃして読みにくくなるので考えてみた。

import FirebaseDatabase

protocol DataBuilder {

    associatedtype Output

    func build(snapshot: DataSnapshot) -> Output?
}

extension DatabaseQuery {

    func observe<B: DataBuilder>(_ type: DataEventType, builder: B, with handler: @escaping (B.Output) -> Void) -> DatabaseHandle {

        return observe(type) { builder.build(snapshot: $0).map(handler) }
    }
}

これで、例えばこう。


struct StringBuilder: DataBuilder {

    func build(snapshot: DataSnapshot) -> String? {

        return snapshot.value as? String
    }
}

すると、すっきりする。


override func viewDidLoad() {

    db = Database.database().reference()

    handler = db.child("child").observe(DataEventType.value, builder: StringBuilder(), queue: .main) { string in

        self.field.stringValue = string
    }
}

追記:
実践的にするにはDataBuilder#build(snapshot:)を throwsに変えて handler を (B.Output, Error) -> Void とするかResultを導入して (Result<B.Output>) -> Voidとするのがいいと思います。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2