我们正在使用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!)
鉴于CChar
是Int8
的别名,我可以使用String
将UnsafePointer<Int8>
转换为.cStringUsingEncoding()
,然后返回String
使用.fromCString(<UnsafePointer_CChar>)
问题是我的SQLite结果是UnsafePointer_UInt8
,无法与.fromCString()
一起使用
最重要的问题是:是否可以将UnsafePointer_UInt8
转换为UnsafePointer_Int8
答案 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))