Pheepster Pheepster - 1 year ago 74
iOS Question

Parameter types not shown correctly from Swift extension

I am replacing some Obj-C in an app where there is a category on NSDictionary and I need the same functionality in a Swift extension. I have written the extension and have a clean build, however when trying to use the extension my parameter type is not recognized. The function takes a parameter of type NSData, but when calling it, passing an NSData object to the function causes a compile error.


extension NSDictionary {
func getJsonDictionaryForData(data:NSData) -> NSDictionary {
var geoDict:NSDictionary = NSDictionary()
do {
geoDict = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary
catch let error as NSError {
print("ERROR: \(error.description)")
return geoDict

When calling the extension's
function, XCode expects the parameter type to be NSDictionary NOT NSData as defined in the extension's function declaration. The screenshot below shows XCode expecting NSDictionary when calling the function. I'm relatively new to Swift extensions so obviously this is an error on my part. Can anyone help me understand why this is happening? Thanks!

// contextData is an NSData object and causes a compile error - wrong data type
let fileDict = NSDictionary.getJsonDictionaryForData(contextData)

enter image description here

Answer Source

You are saying:


as if this were a class method. But in your extension you defined it as an instance method. So:

  • If you wanted a class method, you should have said class func.

  • If you wanted an instance method, you should be calling this method on an actual dictionary, not on the class NSDictionary.

(By the way, what the compiler and the code completion are saying is actually correct, because an instance method in Swift is a curried class method. Thus, when you try to call this instance method as a class method, you are seeing the signature of the hidden class method. But that is probably more technical info than you really need.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download