4

I am using SQLite.swift (Branch Swift-1-2) in my app in XCode 6.3 beta. I am able to create the Database/Tables and insert entries into the tables.

So far so good.

Now when I have a simple scenario as follows:

class Foo {
   var id: Int?
   var name: String?
   /* constructor to create an instance ... */
}

// This is how the table column is defined
var id = Expression<Int64>("id")

// Function to update data in the table
func updateFoo(foo: Foo) -> Int? {
    // 'foos' is the table name
    let candidateFoo = foos.filter(super.id == foo.id!) //<----ERROR!!!
    let (rowsUpdated, statement) = candidateFoo.update(name <- foo.name!)

    if  let rowsUpdated = rowsUpdated {
        println("Succesfully updated \(rowsUpdated) row(s)")
        return rowsUpdated
    } else if statement.failed {
        println("Update failed. Reason: \(statement.reason)")
    }

    return nil
}

On the line commented \\ <----ERROR!!!, I get the compile-time error: Binary operator '==' cannot be applied to operands of type Expression< Int64 > and Int

If I use an Int directly on that line, then that works fine. Eg.

let candidateFoo = foos.filter(super.id == 3) // No Error!

But, if I simply do this, it fails with the same error again:

var i = 3
let candidateFoo = foos.filter(super.id == i) // <----ERROR!!!

I understand what the error is, but I am not able to resolve it. I looked at the documentation but I am still stuck. So any help is appreciated.

Update:

Explicitly declaring the variable as Int64 solves the issue:

var i:Int64 = 3
let candidateFoo = foos.filter(super.id == i) // No Error!

Now I am wondering if I have to change my class definition, which will require changes at multiple places in the code. Also official swift documentation recommends using Int unless an explicit size is required.

You should use the word-sized Int type to store integer values, unless you require a type with a specific size or signedness.

Also, the SQLite.swift documentation states that:

While Int64 is the basic, raw type (to preserve 64-bit integers on 32-bit platforms), Int and Bool work transparently.

So should I be using the Int64 here explicitly in my class definition, since its mapped to a DB?

4

1 回答 1

2

您将Foo结构直接映射到 SQL 中的基础类型,因此您应该在两个地方使用相同的类型。如果您需要 32 位设备上的 64 位精度(以避免溢出等),您应该使用Int64. 如果您不担心,请使用Int这两个地方:

var id = Expression<Int>("id")

如果我直接在该行上使用 Int ,那么效果很好。例如。

这是因为它实际上是一个Int64,它符合IntegerLiteralConvertible因此推断文字的基础类型(您可以在此处阅读有关 Swift 文字可转换的更多信息:http: //nshipster.com/swift-literal-convertible/)。

那么我应该在我的类定义中明确使用 Int64,因为它映射到数据库吗?

请记住,SQLite.swift 表达式层使您可以灵活地引用基础列类型(假设您符合它的Value协议),所以再一次:Int如果您是这样处理的,您可以自由使用整个代码的价值。

除此之外,当您在 Swift 中使用不同的整数类型时,您可以将它们内联转换。例如

let candidateFoo = foos.filter(super.id == Int64(foo.id!))
于 2015-03-15T18:22:11.580 回答