27032

[code]

    var publicKeyBits = Unmanaged<AnyObject>?()
    SecItemCopyMatching(queryAttrs, &publicKeyBits)
    
[/code]

# エラー内容

> Cannot convert value of type 'Unmanaged?' to expected argument type
> 'AnyObject?'

どうやったら使えるようになるでしょうか。

# 追記

[code]

    var result: Unmanaged<AnyObject>?
    let pointer: UnsafeMutablePointer<AnyObject?> = UnsafeMutablePointer((result?.toOpaque())!)
    let status = SecItemCopyMatching(queryAttrs, pointer)
    
[/code]

こう書き換えることでエラーはなくなりましたが、

> Thread1:EXC_BAD_INSTRUCTION (code=EXC_i386_INVOP. subcode0x0)

実行した際にこういうエラーが出ました。


CC BY-SA 3.0
2016-06-24T07:25:09.773
27021
2016-06-24T13:33:46.283
2016-06-24T08:00:48.767
16765
16765
question
swift xcode swift2 xcode7
型の変換について


Cの関数に渡す時は、`AnyObject?`に`&`をつけると、`UnsafeMutablePointer<AnyObject?>`として扱ってくれます。

[code]

    let SecClassValue       = kSecClass     as NSString
    let SecReturnRefValue   = kSecReturnRef as NSString
    let query: NSMutableDictionary = [
        SecClassValue       : kSecClassCertificate,
        SecReturnRefValue   : kCFBooleanTrue,
        // append query
    ]
    var result: AnyObject?
    let status = SecItemCopyMatching(query, &result)
    if status == errSecSuccess {
        // do something
    }
    
[/code]

公式リファレンス using Swift with Cocoa and Objective-C の [Interacting with C
APIs](https://developer.apple.com/library/mac/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8-ID17)を参照してみてください。


CC BY-SA 3.0
2016-06-24T13:33:46.283
27032
2016-06-24T13:33:46.283
5337
27021
answer