如何在 Swift 中添加自定义 sqlite 函数?
以下 SO 问题解决了在涉及坐标的 sqlite 查询中使用 acos 和 cos 等函数的问题: iOS sqlite no such function: ACOS error
建议是增加一个自定义函数。但是这个例子是在 Objective-C 中给出的。除了桥接到 Objective-C 之外,是否有允许创建自定义函数的 native Swift 函数或库?
最佳答案
SQLite.swift为 creating custom SQL functions 提供类型安全的 Swift 接口(interface)(免责声明:我编写并维护了 SQLite.swift)。当前版本在内部桥接到 Objective-C,尽管这是您可以忽略的实现细节。 future 的版本可能会使用 Swift 2 的函数指针 API。虽然您可以在 Swift 1.x 中使用一些 @objc_block
和 unsafeBitCast
中的 C 函数指针,但阅读和维护起来要差得多.
创建cos
函数的最基本方法:
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 为你的数据库生成一个类型安全的接口(interface)给定一个契约(Contract):
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"
关于ios - 单独在 Swift 中创建自定义 sqlite 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30825513/