Caroline Harrison Caroline Harrison - 3 months ago 14
iOS Question

Swift category: "Cannot convert value of type to expected argument type 'AnyObject!'

I'm trying to convert a category in Objective C to swift. I'm not too familiar with even Objective C categories, and now I'm getting the error: "Cannot convert value of type 'SelectionBlock!' to expected argument type of 'AnyObject!'", and I'm not sure where to go from here.

import Foundation
import MapKit
import ObjectiveC

var AssociatedObjectHandle: UInt8 = 0

extension MKPointAnnotation {

typealias SelectionBlock = () -> Void

var selectionBlock: SelectionBlock! {
get {
return objc_getAssociatedObject(self, &AssociatedObjectHandle) as! SelectionBlock
}
set(selectionBlock) {
objc_setAssociatedObject(self, &AssociatedObjectHandle, selectionBlock, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
}
}

}

Answer

Caroline, try to force making selectionBlock in to AnyObject

extension MKPointAnnotation {

    typealias SelectionBlock = () -> Void

    var selectionBlock: SelectionBlock! {
        get {
            return objc_getAssociatedObject(self, &AssociatedObjectHandle) as! SelectionBlock
        }
        set(selectionBlock) {
            objc_setAssociatedObject(self, &AssociatedObjectHandle, selectionBlock as! AnyObject, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
        }
    }

}