我们正在Swift中的iOS中实现SQLite,而不使用包装器或Objective- C桥接。一切正常,除非进行查询并提取结果。问题是UnsafePointer<UInt8>从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>using .cStringUsingEncoding(),然后再转换为Stringusing.fromCString(<UnsafePointer_CChar>)
CChar
Int8
String
UnsafePointer<Int8>
.cStringUsingEncoding()
.fromCString(<UnsafePointer_CChar>)
问题是我的SQLite结果是UnsafePointer_UInt8,不能与.fromCString()
UnsafePointer_UInt8
.fromCString()
最重要的问题是:是否可以将a转换或转换UnsafePointer_UInt8为UnsafePointer_Int8
UnsafePointer_Int8
这应该工作:
let address = sqlite3_column_text(statement, 0) let string = String.fromCString(UnsafePointer<CChar>(address)) let string = String(cString: sqlite3_column_text(statement, 0))
更新:
sqlite3_column_text()返回一个 隐式展开的可选, 这就是为什么您可以将其String(cString:)直接传递给它。
sqlite3_column_text()
String(cString:)
但是根据Column方法,错误和NULL处理#41,返回值 可以 为null(在内存不足的情况下,或者使用NULL列类型调用时)。因此,这样做更安全
if let text = sqlite3_column_text(statement, 0) { let string = String(cString: text) // ... } else { // sqlite3_column_text() returned NULL }