We are implementing SQLite in iOS, in Swift, without using wrappers or Objective-C bridging. Everything works fine, except when doing a query and extracting the result. The issue is with the UnsafePointer<UInt8>
that is returned from SQLite in Swift as follows:
我们在iOS和Swift中实现了SQLite,而不使用包装器或Objective-C桥接。除了在执行查询和提取结果时之外,一切都运行良好。该问题是与UnsafePointer
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)
As you can see, we can convert the pointer to String if we know the length of the object (in this case 10)
如您所见,如果我们知道对象的长度,我们可以将指针转换为String(在本例中为10)
To dig into this issue, I have the following example
要深入研究这个问题,我有以下示例
let pointerFromString: UnsafePointer<Int8> = "xyz".cStringUsingEncoding(NSUTF8StringEncoding)
let stringFromPointer = String.fromCString(anotherPointerFromString_Int8) println(stringFromPointer!)
Given that CChar
is an alias of Int8
, I can convert a String
to UnsafePointer<Int8>
using .cStringUsingEncoding()
, and then back to String
using .fromCString(<UnsafePointer_CChar>)
假设CChar是Int8的别名,我可以使用.cStringUsingEncoding()将一个字符串转换为UnsafePointer
The problem is that my SQLite result is a UnsafePointer_UInt8
, that can´t be used with .fromCString()
问题是我的SQLite结果是UnsafePointer_UInt8,´t可以使用.fromCString()
The bottom line question is: Is it possible to convert or cast a UnsafePointer_UInt8
to UnsafePointer_Int8
底线问题是:是否可能将UnsafePointer_UInt8转换或转换为UnsafePointer_Int8
1 个解决方案
#1
17
This should work:
这应该工作:
let address = sqlite3_column_text(statement, 0)
let string = String.fromCString(UnsafePointer<CChar>(address))
Update for Swift 3 (Xcode 8), compare Swift 3: convert a null-terminated UnsafePointer<UInt8> to a string:
更新Swift 3 (Xcode 8),比较Swift 3:将空终止的UnsafePointer
let string = String(cString: sqlite3_column_text(statement, 0))
#1
17
This should work:
这应该工作:
let address = sqlite3_column_text(statement, 0)
let string = String.fromCString(UnsafePointer<CChar>(address))
Update for Swift 3 (Xcode 8), compare Swift 3: convert a null-terminated UnsafePointer<UInt8> to a string:
更新Swift 3 (Xcode 8),比较Swift 3:将空终止的UnsafePointer
let string = String(cString: sqlite3_column_text(statement, 0))