Issue with UnsafePointer in SQLite project in Swift

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
}

Leave a Comment