UnsafePointer<Uint8> 的问题在 Swift 的 SQLite 项目中 [英] Issue with UnsafePointer<Uint8> in SQLite project in Swift
问题描述
我们正在 iOS 和 Swift 中实现 SQLite,不使用包装器或 Objective-C 桥接.一切正常,除了在执行查询和提取结果时.问题在于从 Swift 中的 SQLite 返回的 UnsafePointer
如下:
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:
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
As you can see, we can convert the pointer to String if we know the length of the object (in this case 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!)
鉴于 CChar
是 Int8
的别名,我可以将 String
转换为 UnsafePointer
使用 .cStringUsingEncoding()
,然后使用 .fromCString(
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>)
问题是我的 SQLite 结果是一个 UnsafePointer_UInt8
,不能与 .fromCString()
The problem is that my SQLite result is a UnsafePointer_UInt8
, that can´t be used with .fromCString()
底线问题是:是否可以将 UnsafePointer_UInt8
转换或转换为 UnsafePointer_Int8
The bottom line question is: Is it possible to convert or cast a UnsafePointer_UInt8
to UnsafePointer_Int8
推荐答案
这应该有效:
let address = sqlite3_column_text(statement, 0)
let string = String.fromCString(UnsafePointer<CChar>(address))
Swift 3 (Xcode 8) 的更新, 比较 Swift 3:转换以空字符结尾的 UnsafePointer
let string = String(cString: sqlite3_column_text(statement, 0))
更新:
sqlite3_column_text()
返回一个隐式解包的可选项,这就是您可以将它直接传递给 String(cString:)
的原因.
sqlite3_column_text()
returns an implicitly unwrapped optional, and that is why you can pass it to String(cString:)
directly.
但根据列方法、错误和NULL处理#41,返回value 可以 为 null(在内存不足的情况下,或者如果使用 NULL 列类型调用).因此这样做更安全
But according to Column methods, error and NULL handling #41, the return value can be null (in an out-of-memory situation, or if called with a NULL column type). Therefore it is safer to do
if let text = sqlite3_column_text(statement, 0) {
let string = String(cString: text)
// ...
} else {
// sqlite3_column_text() returned NULL
}
这篇关于UnsafePointer<Uint8> 的问题在 Swift 的 SQLite 项目中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!