No exact matches in call to initializer with UnsafeMutablePointer

218 views Asked by At

I'm trying to make an unsafeMutablePointer with a context, and I'm getting the error "No exact matches in call to initializer". Not sure what is going on here. Working off this answer.

let context = UIGraphicsGetCurrentContext()

var pixels:Any?

if let data = context?.data
{
  pixels = UnsafeMutablePointer<CUnsignedChar>(data) // No exact matches in call to initializer
}
1

There are 1 answers

1
OOPer On

This answer was written 5 years ago, which is too old in the Swift world.

I could not find a right answer searching with No exact matches in call to initializer with UnsafeMutablePointer, but there would be many articles about pointer handling when Swift changed the way how to convert the pointee type of pointers.

Please try this one:

        let context = UIGraphicsGetCurrentContext()

        var pixels: UnsafeMutablePointer<CUnsignedChar>? = nil

        if let data = context?.data {
            pixels = data.assumingMemoryBound(to: CUnsignedChar.self) //<-
        }

(You should better not use Any as far as you can.)