Swift中的SQLite项目中的UnsafePointer <uint8>问题</uint8>

时间:2014-08-06 18:54:02

标签: ios sqlite pointers swift

我们正在使用Swift在iOS中实现SQLite,而不使用包装器或Objective-C桥接。一切正常,除了在进行查询和提取结果时。问题在于,在Swift中从SQLite返回的UnsafePointer<UInt8>如下:

var querySQL = "SELECT address, phone FROM CONTACTS WHERE NAME = 'myName'"
var cQuery = querySQL.cStringUsingEncoding(NSUTF8StringEncoding)
var statement: COpaquePointer = nil
if sqlite3_prepare_v2(contactsDB, cQuery!, -1, &statement, nil) == SQLITE_OK {
   if sqlite3_step(statement) == SQLITE_ROW {
   var address : UnsafePointer<UInt8> = sqlite3_column_text(statement, 0)
   var data = NSData(bytes: address, length: 10)
   var string = NSString(data: data, encoding: NSUTF8StringEncoding)
   println(string)

如您所见,如果我们知道对象的长度(在本例中为10),我们可以将指针转换为String

要深入研究这个问题,我有以下示例

let pointerFromString: UnsafePointer<Int8> = "xyz".cStringUsingEncoding(NSUTF8StringEncoding)
let stringFromPointer = String.fromCString(anotherPointerFromString_Int8)                    println(stringFromPointer!)

鉴于CCharInt8的别名,我可以使用StringUnsafePointer<Int8>转换为.cStringUsingEncoding(),然后返回String使用.fromCString(<UnsafePointer_CChar>)

问题是我的SQLite结果是UnsafePointer_UInt8,无法与.fromCString()一起使用

最重要的问题是:是否可以将UnsafePointer_UInt8转换为UnsafePointer_Int8

1 个答案:

答案 0 :(得分:17)

这应该有效:

let address = sqlite3_column_text(statement, 0)
let string = String.fromCString(UnsafePointer<CChar>(address))

更新Swift 3(Xcode 8),比较Swift 3: convert a null-terminated UnsafePointer<UInt8> to a string

let string = String(cString: sqlite3_column_text(statement, 0))