Issue with UnsafePointer in SQLite project in Swift

后端 未结 1 1833
轮回少年
轮回少年 2020-11-30 13:18

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

相关标签:
1条回答
  • 2020-11-30 13:50

    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:

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

    Update:

    sqlite3_column_text() returns an implicitly unwrapped optional, and that is why you can pass it to String(cString:) directly.

    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
    }
    
    0 讨论(0)
提交回复
热议问题