ios - 单独在 Swift 中创建自定义 sqlite 函数

标签 ios sqlite swift

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

以下 SO 问题解决了在涉及坐标的 sqlite 查询中使用 acos 和 cos 等函数的问题: iOS sqlite no such function: ACOS error

建议是增加一个自定义函数。但是这个例子是在 Objective-C 中给出的。除了桥接到 Objective-C 之外,是否有允许创建自定义函数的 native Swift 函数或库?

最佳答案

SQLite.swiftcreating custom SQL functions 提供类型安全的 Swift 接口(interface)(免责声明:我编写并维护了 SQLite.swift)。当前版本在内部桥接到 Objective-C,尽管这是您可以忽略的实现细节。 future 的版本可能会使用 Swift 2 的函数指针 API。虽然您可以在 Swift 1.x 中使用一些 @objc_blockunsafeBitCast 中的 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/

相关文章:

ios - 根据从 TableView 中选择的内容将 View Controller 嵌入到容器 View 中

java - 如果日期不在 Android 的该表中,如何将日期插入用户输入的表中

不同 DBMS 中的 SQL

ios - 验证收据 iOS

ios - 保存当前 GIDGoogleUser 而不是在每次启动时登录

ios - 搜索 CoreData 以匹配 NSDate - Swift

ios - iOS项目提供 “Automatic Reference Count Issue”

Swift:类型符合 Equatable 的泛型数组

iphone - 当 View 变得可见时,UITextField 成为第一响应者,但我不希望它

android - 在 android 中更改现有 db4o 中的类属性