How to Initialize OpaquePointer in Swift
I want to use OpaquePointer in Swift. This is my Code.
@State var OP : OpaquePointer = OpaquePointer.init(bitPattern: <#T##Int#>)
In my Project, I use SwiftGit2 Library. And because of that, I must initialize the OpaquePointer.
It doesn't matter what way.
In addition, I put any bitPatter in the Parameter. And, here is the Error
@State var OP : OpaquePointer = OpaquePointer.init(bitPattern: 1)
Value of optional type 'OpaquePointer?' must be unwrapped to a value of type 'OpaquePointer'
Thank you.
Solution 1:
What the compile error is telling you is that the initialiser that takes a bit pattern returns an optional OpaquePointer
.
So you either should use it as an optional:
@State var OP: OpaquePointer? = OpaquePointer(bitPattern: 1)
Or if you're a 100% certain the opaque pointer is never nil, you can force unwrap it:
@State var OP: OpaquePointer = OpaquePointer(bitPattern: 1)!
However, if the OpaquePointer
fails to initialise, your app will crash.
Please note that a bitPattern of 1 will most certainly fail, since this should point to an address in memory.
A better way to get an OpaquePointer is to derive it from an UnsafePointer
or UnsafeMutablePointer
, so you're sure the pointer is actually pointing to the thing you want it to.
What are you trying to point to? And do you really need an OpaquePointer
? If so, I'd highly advise to not mess with pointers inside your SwiftUI view, do this stuff in a (or multiple) layers 'above' that (so either ViewModel or Model/Data).