i've been using sqlite.swift lately build app database. , i'm defining integer
columns int64
type, documentation explains.
but every once in while need int64
int
. question is, if this:
//create table int instead of int64 let test_id = expression<int>("test_id") let tests = db["tests"] db.create(table: tests, ifnotexists: true){ t in t.column(test_id) } class func inserttest(t: int) -> int{ //insert.rowid returns int64 type let insert = tests.insert(test_id <- t) if let rowid = insert.rowid{ //directly cast int64 int return int(rowid) } return 0 }
will correct?
of course tested it. , works, reading this question in stackoverflow
and seems have problem 32 bits devices...
if wrong, how can cast int64
int
?
converting int64
int
passing int64
value int
initializer work on 64-bit machine, , crash on 32-bit machine if integer outside of range int32.min ... int32.max
.
for safety use init(truncatingbitpattern)
initializer convert value:
return int(truncatingbitpattern: rowid)
on 64-bit machine, truncatingbitpattern
nothing; int
(which same size int64
anyway).
on 32-bit machine, throw away top 32 bits, zeroes, haven't lost data. long value fit 32-bit int
, can without losing data. if value outside of range int32.min ... int32.max
, change value of int64
fits in 32-bit int
, not crash.
you can see how works in playground. since int
in playground 64-bit int
, can explicitly use int32
simulate behavior of 32-bit system.
let i: int64 = 12345678901 // value bigger maximum 32-bit int let j = int32(truncatingbitpattern: i) // j = -539,222,987 let k = int32(i) // crash!
update swift 3
in addition init(truncating:)
still works, swift 3 introduces failable initializers safely convert 1 integer type another. using init?(exactly:)
can pass 1 type initialize another, , returns nil
if initialization fails. value returned optional must unwrapped in usual ways.
for example:
let i: int64 = 12345678901 if let j = int32(exactly: i) { print("\(j) fits int32") } else { // initialization returned nil print("\(i) large int32") }
this allows apply nil coalescing operator supply default value if conversion fails:
// return 0 if rowid big fit int on device return int(exactly: rowid) ?? 0
Comments
Post a Comment