UnsafeMutablePointer<CFTypeRef> in Swift 3

与世无争的帅哥 提交于 2019-12-01 18:29:22
OOPer

In your case, you do not need to use withMemoryRebound or withUnsafeMutablePointer(to:).

Instead, you can just use

var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)

if status == noErr, let data = result as? Data {
    //use data...
}

Generally, when you need to pass an UnsafeMutablePointer<T> to a function, declare a variable of type T and pass it as an inout argument &variable. In your case, T is CFTypeRef?, and in Swift 3, CFTypeRef is just a typealias of AnyObject.


Even in Swift 2.2, you did not need to use withUnsafeMutablePointer

var result: AnyObject?  
let status = SecItemCopyMatching(query, &result)  

The error message is somewhat misleading - the actual problem is that result has to be an AnyObject? - withMemoryRebound doesn't need to be used.

var result: AnyObject?
let status = withUnsafeMutablePointer(to: &result){
    SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}

Works as expected and gets the correct result from keychain - it just needs to be casted to Data. In fact, withUnsafeMutablePointer doesn't even have to be used.

So, my new code is

var query: [String : AnyObject] = [:]
//set up the query

var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)

var data: Data?
if status == noErr{
    data = result as? Data
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!