Problem to use UnsafePointer<Int8>

Hello friends.


I tried write the below line on swift 3:


let text = UnsafePointer<Int8>(sqlite3_column_text(statement, index))


But I have this error:

'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.


I thinh that Tthis error is about UnsafePointer<Int8>

How cain I fix it?

Answered by DTS Engineer in 194660022

This is fallout from SE-0107 UnsafeRawPointer API, which puts Swift’s type aliasing rules on a firm footing. I recommend you read the UnsafeRawPointer Migration doc before going further here.

You wrote:

I think that this error is about

UnsafePointer<Int8>

Right. Swift 3 no longer lets you construct pointers of type A from pointers of type B, and in this case

sqlite3_column_text
returns a pointer to type
UInt8
.

There are a bunch of ways to fix this but the best approach depends on what you’re doing with the returned value. For example, if your final goạl is to get a Swift string, you can avoid the whole issue by using string initialisation function that takes an

UnsafePointer<UInt8>
.
let text = sqlite3_column_text(statement, index)
// `text` is of type `UnsafePointer<UInt8>`
if let text = text {
    let str = String(cString: text)
    …
} else {
    … handle the fact that text is nil …
}

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Accepted Answer

This is fallout from SE-0107 UnsafeRawPointer API, which puts Swift’s type aliasing rules on a firm footing. I recommend you read the UnsafeRawPointer Migration doc before going further here.

You wrote:

I think that this error is about

UnsafePointer<Int8>

Right. Swift 3 no longer lets you construct pointers of type A from pointers of type B, and in this case

sqlite3_column_text
returns a pointer to type
UInt8
.

There are a bunch of ways to fix this but the best approach depends on what you’re doing with the returned value. For example, if your final goạl is to get a Swift string, you can avoid the whole issue by using string initialisation function that takes an

UnsafePointer<UInt8>
.
let text = sqlite3_column_text(statement, index)
// `text` is of type `UnsafePointer<UInt8>`
if let text = text {
    let str = String(cString: text)
    …
} else {
    … handle the fact that text is nil …
}

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Problem to use UnsafePointer&lt;Int8&gt;
 
 
Q