单独在Swift中创build自定义的sqlite函数

如何在Swift中添加一个自定义的sqlite函数?

下面的SO问题解决了在涉及坐标的sqlite查询中使用像acos和cos 这样的函数的问题:iOS sqlite没有这样的函数:ACOS错误

build议是添加一个自定义函数。 但是这个例子在Objective-C中给出。 除了桥接到Objective-C有一个本地的Swift函数或库,允许创build自定义函数?

SQLite.swift提供了一个用于创build自定义SQL函数的types安全的Swift接口(免责声明:我编写和维护了SQLite.swift) 。 当前版本在内部桥接到Objective-C,尽pipe这是一个可以忽略的实现细节。 未来的版本可能会使用Swift 2的函数指针API。 虽然你可以在Swift 1.x中使用C函数指针和一些@objc_blockunsafeBitCast ,但是读取和维护会更糟糕。

创buildcos函数的最基本的方法是:

 import SQLite import Darwin // opens a database connection let db = Database() // defines a "cos" function on the connection db.create(function: "cos", argc: 1, deterministic: true) { args in if let x = args[0] as? Double { return Darwin.cos(x) } return nil } println(db.scalar("SELECT cos(1.0)")) // Optional(0.54030230586813977) 

一个更复杂,更安全的例子,其中SQLite.swift根据合同为您的数据库生成一个types安全的接口:

 import SQLite import Darwin // opens a database connection let db = Database() // defines a "cos" function on the connection let cos: Expression<Double> -> Expression<Double> = ( db.create(function: "cos", deterministic: true, Darwin.cos) ) // builds a SQL expression for the column, "x" let x = Expression<Double>("x") // creates a query reference for the table, "table" let table = db["table"] // creates the table db.create(table: table) { t in t.column(x) } // CREATE TABLE "table" ("x" REAL) // inserts a row where "x" is 1.0 table.insert(x <- 1.0) // INSERT INTO "table" ("x") VALUES (1.0) // executes the query for row in db.select(cos(x)) { println(row[cos(x)]) } // SELECT "cos"("x") FROM "table"