Pārlūkot izejas kodu

Updated README for Swift 3

Robert M. Ryan 9 gadi atpakaļ
vecāks
revīzija
add5a00f43
1 mainītis faili ar 38 papildinājumiem un 3 dzēšanām
  1. 38 3
      README.markdown

+ 38 - 3
README.markdown

@@ -315,11 +315,46 @@ To do this, you must:
 
 4. Use the variations of `executeQuery` and `executeUpdate` with the `sql` and `values` parameters with `try` pattern, as shown below. These renditions of `executeQuery` and `executeUpdate` both `throw` errors in true Swift 2 fashion.
 
-If you do the above, you can then write Swift code that uses `FMDatabase`. For example:
+If you do the above, you can then write Swift code that uses `FMDatabase`. For example, in Swift 3:
+
+let fileURL = try! FileManager.default
+    .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
+    .appendingPathComponent("test.sqlite")
+
+guard let database = FMDatabase(path: fileURL.path) else {
+    print("unable to create database")
+    return
+}
+
+guard database.open() else {
+    print("Unable to open database")
+    return
+}
+
+do {
+    try database.executeUpdate("create table test(x text, y text, z text)", values: nil)
+    try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["a", "b", "c"])
+    try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["e", "f", "g"])
+
+    let rs = try database.executeQuery("select x, y, z from test", values: nil)
+    while rs.next() {
+        if let x = rs.string(forColumn: "x"), let y = rs.string(forColumn: "y"), let z = rs.string(forColumn: "z") {
+            print("x = \(x); y = \(y); z = \(z)")
+        }
+    }
+} catch {
+    print("failed: \(error.localizedDescription)")
+}
+
+database.close()
+```
+
+Or in Swift 2:
 
 ```swift
-let documents = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
-let fileURL = documents.URLByAppendingPathComponent("test.sqlite")
+let fileURL = try! NSFileManager.defaultManager()
+    .URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
+    .URLByAppendingPathComponent("test.sqlite")
 
 let database = FMDatabase(path: fileURL.path)