aboutsummaryrefslogtreecommitdiffhomepage
path: root/Firestore/Example/SwiftBuildTest/main.swift
diff options
context:
space:
mode:
authorGravatar Gil <mcg@google.com>2018-02-26 10:51:58 -0800
committerGravatar GitHub <noreply@github.com>2018-02-26 10:51:58 -0800
commitac06a94ace327601474ff15a2fb98824ca49e832 (patch)
tree1a96b61ccdd64917f3b8e41c25e66f3c7236e414 /Firestore/Example/SwiftBuildTest/main.swift
parentd4ec10577a40e8a913070cf40a29636c41aafbd2 (diff)
Auto-style swift sources (#847)
* Fix bash style issues * Exclude additional build output directories * Format swift files with scripts/style.sh * Reformat swift sources * Allow swiftformat 0.32.0 on travis
Diffstat (limited to 'Firestore/Example/SwiftBuildTest/main.swift')
-rw-r--r--Firestore/Example/SwiftBuildTest/main.swift450
1 files changed, 220 insertions, 230 deletions
diff --git a/Firestore/Example/SwiftBuildTest/main.swift b/Firestore/Example/SwiftBuildTest/main.swift
index 260735b..cd2462b 100644
--- a/Firestore/Example/SwiftBuildTest/main.swift
+++ b/Firestore/Example/SwiftBuildTest/main.swift
@@ -19,223 +19,215 @@ import Foundation
import FirebaseFirestore
func main() {
- let db = initializeDb();
+ let db = initializeDb()
- let (collectionRef, documentRef) = makeRefs(database: db);
+ let (collectionRef, documentRef) = makeRefs(database: db)
- let query = makeQuery(collection: collectionRef);
+ let query = makeQuery(collection: collectionRef)
- writeDocument(at: documentRef);
+ writeDocument(at: documentRef)
- writeDocuments(at: documentRef, database: db);
+ writeDocuments(at: documentRef, database: db)
- addDocument(to: collectionRef);
+ addDocument(to: collectionRef)
- readDocument(at: documentRef);
+ readDocument(at: documentRef)
- readDocuments(matching: query);
+ readDocuments(matching: query)
- listenToDocument(at: documentRef);
+ listenToDocument(at: documentRef)
- listenToDocuments(matching: query);
+ listenToDocuments(matching: query)
- enableDisableNetwork(database: db);
+ enableDisableNetwork(database: db)
- types();
+ types()
}
func initializeDb() -> Firestore {
+ // Initialize with ProjectID.
+ let firestore = Firestore.firestore()
- // Initialize with ProjectID.
- let firestore = Firestore.firestore()
+ // Apply settings
+ let settings = FirestoreSettings()
+ settings.host = "localhost"
+ settings.isPersistenceEnabled = true
+ firestore.settings = settings
- // Apply settings
- let settings = FirestoreSettings()
- settings.host = "localhost"
- settings.isPersistenceEnabled = true
- firestore.settings = settings
-
- return firestore;
+ return firestore
}
func makeRefs(database db: Firestore) -> (CollectionReference, DocumentReference) {
+ var collectionRef = db.collection("my-collection")
- var collectionRef = db.collection("my-collection")
-
- var documentRef: DocumentReference;
- documentRef = collectionRef.document("my-doc")
- // or
- documentRef = db.document("my-collection/my-doc")
+ var documentRef: DocumentReference
+ documentRef = collectionRef.document("my-doc")
+ // or
+ documentRef = db.document("my-collection/my-doc")
- // deeper collection (my-collection/my-doc/some/deep/collection)
- collectionRef = documentRef.collection("some/deep/collection")
+ // deeper collection (my-collection/my-doc/some/deep/collection)
+ collectionRef = documentRef.collection("some/deep/collection")
- // parent doc (my-collection/my-doc/some/deep)
- documentRef = collectionRef.parent!
+ // parent doc (my-collection/my-doc/some/deep)
+ documentRef = collectionRef.parent!
- // print paths.
- print("Collection: \(collectionRef.path), document: \(documentRef.path)")
+ // print paths.
+ print("Collection: \(collectionRef.path), document: \(documentRef.path)")
- return (collectionRef, documentRef);
+ return (collectionRef, documentRef)
}
func makeQuery(collection collectionRef: CollectionReference) -> Query {
-
- let query = collectionRef.whereField(FieldPath(["name"]), isEqualTo: "Fred")
- .whereField("age", isGreaterThanOrEqualTo: 24)
- .whereField(FieldPath.documentID(), isEqualTo: "fred")
- .order(by: FieldPath(["age"]))
- .order(by: "name", descending: true)
- .limit(to: 10)
-
- return query;
+ let query = collectionRef.whereField(FieldPath(["name"]), isEqualTo: "Fred")
+ .whereField("age", isGreaterThanOrEqualTo: 24)
+ .whereField(FieldPath.documentID(), isEqualTo: "fred")
+ .order(by: FieldPath(["age"]))
+ .order(by: "name", descending: true)
+ .limit(to: 10)
+
+ return query
}
func writeDocument(at docRef: DocumentReference) {
-
- let setData = [
- "foo": 42,
- "bar": [
- "baz": "Hello world!"
- ]
- ] as [String : Any];
-
- let updateData = [
- "bar.baz": 42,
- FieldPath(["foobar"]) : 42
- ] as [AnyHashable : Any];
-
- docRef.setData(setData)
-
- // Completion callback (via trailing closure syntax).
- docRef.setData(setData) { error in
- if let error = error {
- print("Uh oh! \(error)")
- return
- }
-
- print("Set complete!")
+ let setData = [
+ "foo": 42,
+ "bar": [
+ "baz": "Hello world!",
+ ],
+ ] as [String: Any]
+
+ let updateData = [
+ "bar.baz": 42,
+ FieldPath(["foobar"]): 42,
+ ] as [AnyHashable: Any]
+
+ docRef.setData(setData)
+
+ // Completion callback (via trailing closure syntax).
+ docRef.setData(setData) { error in
+ if let error = error {
+ print("Uh oh! \(error)")
+ return
}
- // SetOptions
- docRef.setData(setData, options:SetOptions.merge())
+ print("Set complete!")
+ }
- docRef.updateData(updateData)
- docRef.delete();
+ // SetOptions
+ docRef.setData(setData, options: SetOptions.merge())
- docRef.delete() { error in
- if let error = error {
- print("Uh oh! \(error)")
- return
- }
+ docRef.updateData(updateData)
+ docRef.delete()
- print("Set complete!")
+ docRef.delete { error in
+ if let error = error {
+ print("Uh oh! \(error)")
+ return
}
+
+ print("Set complete!")
+ }
}
func enableDisableNetwork(database db: Firestore) {
- // closure syntax
- db.disableNetwork(completion: { (error) in
- if let e = error {
- print("Uh oh! \(e)")
- return
- }
- })
- // trailing block syntax
- db.enableNetwork { (error) in
- if let e = error {
- print("Uh oh! \(e)")
- return
- }
+ // closure syntax
+ db.disableNetwork(completion: { error in
+ if let e = error {
+ print("Uh oh! \(e)")
+ return
}
+ })
+ // trailing block syntax
+ db.enableNetwork { error in
+ if let e = error {
+ print("Uh oh! \(e)")
+ return
+ }
+ }
}
func writeDocuments(at docRef: DocumentReference, database db: Firestore) {
- var batch: WriteBatch;
+ var batch: WriteBatch
- batch = db.batch();
- batch.setData(["a" : "b"], forDocument:docRef);
- batch.setData(["c" : "d"], forDocument:docRef);
+ batch = db.batch()
+ batch.setData(["a": "b"], forDocument: docRef)
+ batch.setData(["c": "d"], forDocument: docRef)
// commit without completion callback.
- batch.commit();
- print("Batch write without completion complete!");
+ batch.commit()
+ print("Batch write without completion complete!")
- batch = db.batch();
- batch.setData(["a" : "b"], forDocument:docRef);
- batch.setData(["c" : "d"], forDocument:docRef);
+ batch = db.batch()
+ batch.setData(["a": "b"], forDocument: docRef)
+ batch.setData(["c": "d"], forDocument: docRef)
// commit with completion callback via trailing closure syntax.
- batch.commit() { error in
+ batch.commit { error in
if let error = error {
- print("Uh oh! \(error)");
- return;
+ print("Uh oh! \(error)")
+ return
}
- print("Batch write callback complete!");
+ print("Batch write callback complete!")
}
- print("Batch write with completion complete!");
+ print("Batch write with completion complete!")
}
func addDocument(to collectionRef: CollectionReference) {
-
- collectionRef.addDocument(data: ["foo": 42]);
- //or
- collectionRef.document().setData(["foo": 42]);
+ collectionRef.addDocument(data: ["foo": 42])
+ // or
+ collectionRef.document().setData(["foo": 42])
}
func readDocument(at docRef: DocumentReference) {
-
- // Trailing closure syntax.
- docRef.getDocument() { document, error in
- if let document = document {
- // Note that both document and document.data() is nullable.
- if let data = document.data() {
- print("Read document: \(data)")
- }
- if let data = document.data(with:SnapshotOptions.serverTimestampBehavior(.estimate)) {
- print("Read document: \(data)")
- }
- if let foo = document.get("foo") {
- print("Field: \(foo)")
- }
- if let foo = document.get("foo", options: SnapshotOptions.serverTimestampBehavior(.previous)) {
- print("Field: \(foo)")
- }
- // Fields can also be read via subscript notation.
- if let foo = document["foo"] {
- print("Field: \(foo)")
- }
- } else {
- // TODO(mikelehen): There may be a better way to do this, but it at least demonstrates
- // the swift error domain / enum codes are renamed appropriately.
- if let errorCode = error.flatMap({
- ($0._domain == FirestoreErrorDomain) ? FirestoreErrorCode (rawValue: $0._code) : nil
- }) {
- switch errorCode {
- case .unavailable:
- print("Can't read document due to being offline!")
- case _:
- print("Failed to read.")
- }
- } else {
- print("Unknown error!")
- }
+ // Trailing closure syntax.
+ docRef.getDocument { document, error in
+ if let document = document {
+ // Note that both document and document.data() is nullable.
+ if let data = document.data() {
+ print("Read document: \(data)")
+ }
+ if let data = document.data(with: SnapshotOptions.serverTimestampBehavior(.estimate)) {
+ print("Read document: \(data)")
+ }
+ if let foo = document.get("foo") {
+ print("Field: \(foo)")
+ }
+ if let foo = document.get("foo", options: SnapshotOptions.serverTimestampBehavior(.previous)) {
+ print("Field: \(foo)")
+ }
+ // Fields can also be read via subscript notation.
+ if let foo = document["foo"] {
+ print("Field: \(foo)")
+ }
+ } else {
+ // TODO(mikelehen): There may be a better way to do this, but it at least demonstrates
+ // the swift error domain / enum codes are renamed appropriately.
+ if let errorCode = error.flatMap({
+ ($0._domain == FirestoreErrorDomain) ? FirestoreErrorCode(rawValue: $0._code) : nil
+ }) {
+ switch errorCode {
+ case .unavailable:
+ print("Can't read document due to being offline!")
+ case _:
+ print("Failed to read.")
}
-
+ } else {
+ print("Unknown error!")
+ }
}
+ }
}
func readDocuments(matching query: Query) {
- query.getDocuments() { querySnapshot, error in
- // TODO(mikelehen): Figure out how to make "for..in" syntax work
- // directly on documentSet.
- for document in querySnapshot!.documents {
- print(document.data())
- }
+ query.getDocuments { querySnapshot, error in
+ // TODO(mikelehen): Figure out how to make "for..in" syntax work
+ // directly on documentSet.
+ for document in querySnapshot!.documents {
+ print(document.data())
}
+ }
}
func listenToDocument(at docRef: DocumentReference) {
-
- let listener = docRef.addSnapshotListener() { document, error in
+ let listener = docRef.addSnapshotListener { document, error in
if let error = error {
print("Uh oh! Listen canceled: \(error)")
return
@@ -243,8 +235,8 @@ func listenToDocument(at docRef: DocumentReference) {
if let document = document {
// Note that document.data() is nullable.
- if let data : [String:Any] = document.data() {
- print("Current document: \(data)");
+ if let data: [String: Any] = document.data() {
+ print("Current document: \(data)")
}
if document.metadata.isFromCache {
print("From Cache")
@@ -255,100 +247,98 @@ func listenToDocument(at docRef: DocumentReference) {
}
// Unsubscribe.
- listener.remove();
+ listener.remove()
}
func listenToDocuments(matching query: Query) {
+ let listener = query.addSnapshotListener { snap, error in
+ if let error = error {
+ print("Uh oh! Listen canceled: \(error)")
+ return
+ }
- let listener = query.addSnapshotListener() { snap, error in
- if let error = error {
- print("Uh oh! Listen canceled: \(error)")
- return
- }
-
- if let snap = snap {
- print("NEW SNAPSHOT (empty=\(snap.isEmpty) count=\(snap.count)")
+ if let snap = snap {
+ print("NEW SNAPSHOT (empty=\(snap.isEmpty) count=\(snap.count)")
- // TODO(mikelehen): Figure out how to make "for..in" syntax work
- // directly on documentSet.
- for document in snap.documents {
- // Note that document.data() is not nullable.
- let data : [String:Any] = document.data()
- print("Doc: ", data)
- }
- }
+ // TODO(mikelehen): Figure out how to make "for..in" syntax work
+ // directly on documentSet.
+ for document in snap.documents {
+ // Note that document.data() is not nullable.
+ let data: [String: Any] = document.data()
+ print("Doc: ", data)
+ }
}
+ }
- // Unsubscribe
- listener.remove();
+ // Unsubscribe
+ listener.remove()
}
func listenToQueryDiffs(onQuery query: Query) {
-
- let listener = query.addSnapshotListener() { snap, error in
- if let snap = snap {
- for change in snap.documentChanges {
- switch (change.type) {
- case .added:
- print("New document: \(change.document.data())")
- case .modified:
- print("Modified document: \(change.document.data())")
- case .removed:
- print("Removed document: \(change.document.data())")
- }
- }
+ let listener = query.addSnapshotListener { snap, error in
+ if let snap = snap {
+ for change in snap.documentChanges {
+ switch change.type {
+ case .added:
+ print("New document: \(change.document.data())")
+ case .modified:
+ print("Modified document: \(change.document.data())")
+ case .removed:
+ print("Removed document: \(change.document.data())")
}
+ }
}
+ }
- // Unsubscribe
- listener.remove();
+ // Unsubscribe
+ listener.remove()
}
func transactions() {
- let db = Firestore.firestore()
-
- let collectionRef = db.collection("cities")
- let accA = collectionRef.document("accountA")
- let accB = collectionRef.document("accountB")
- let amount = 20.0
-
- db.runTransaction({ (transaction, errorPointer) -> Any? in
- do {
- let balanceA = try transaction.getDocument(accA)["balance"] as! Double
- let balanceB = try transaction.getDocument(accB)["balance"] as! Double
-
- if balanceA < amount {
- errorPointer?.pointee = NSError(domain: "Foo", code: 123, userInfo: nil)
- return nil
- }
- transaction.updateData(["balance": balanceA - amount], forDocument:accA)
- transaction.updateData(["balance": balanceB + amount], forDocument:accB)
- } catch let error as NSError {
- print("Uh oh! \(error)")
- }
- return 0
- }) { (result, error) in
- // handle result.
+ let db = Firestore.firestore()
+
+ let collectionRef = db.collection("cities")
+ let accA = collectionRef.document("accountA")
+ let accB = collectionRef.document("accountB")
+ let amount = 20.0
+
+ db.runTransaction({ (transaction, errorPointer) -> Any? in
+ do {
+ let balanceA = try transaction.getDocument(accA)["balance"] as! Double
+ let balanceB = try transaction.getDocument(accB)["balance"] as! Double
+
+ if balanceA < amount {
+ errorPointer?.pointee = NSError(domain: "Foo", code: 123, userInfo: nil)
+ return nil
+ }
+ transaction.updateData(["balance": balanceA - amount], forDocument: accA)
+ transaction.updateData(["balance": balanceB + amount], forDocument: accB)
+ } catch let error as NSError {
+ print("Uh oh! \(error)")
}
+ return 0
+ }) { result, error in
+ // handle result.
+ }
}
func types() {
- let _: CollectionReference;
- let _: DocumentChange;
- let _: DocumentListenOptions;
- let _: DocumentReference;
- let _: DocumentSnapshot;
- let _: FieldPath;
- let _: FieldValue;
- let _: Firestore;
- let _: FirestoreSettings;
- let _: GeoPoint;
- let _: ListenerRegistration;
- let _: QueryListenOptions;
- let _: Query;
- let _: QuerySnapshot;
- let _: SetOptions;
- let _: SnapshotMetadata;
- let _: Transaction;
- let _: WriteBatch;
+ let _: CollectionReference
+ let _: DocumentChange
+ let _: DocumentListenOptions
+ let _: DocumentReference
+ let _: DocumentSnapshot
+ let _: FieldPath
+ let _: FieldValue
+ let _: Firestore
+ let _: FirestoreSettings
+ let _: GeoPoint
+ let _: ListenerRegistration
+ let _: QueryListenOptions
+ let _: Query
+ let _: QuerySnapshot
+ let _: SetOptions
+ let _: SnapshotMetadata
+ let _: Transaction
+ let _: WriteBatch
}