简体   繁体   中英

Accessing Swift Extension From Objective-C

I'm having trouble accessing my swift extension from objective-c.

I have the following code in a .swift file:

extension NSDictionary {
    func dictionaryAsJsonString() -> NSString {
        var err: NSError?
        var data = NSJSONSerialization.dataWithJSONObject(self, options: NSJSONWritingOptions.PrettyPrinted, error: &err)
        var string = NSString(data: data, encoding: NSUTF8StringEncoding)
        return string
    }
}

I'm expecting to be able to do the following in my .m file:

[dictionary dictionaryAsJsonString];

but it can't find my method and doesn't autocomplete.

I know my imports are working fine because I'm able to access my other swift objects.

It is easy enough using simply a Dictionary

 20> extension Dictionary {
 21.     func toJSONString () -> String { return "my dictionary" }
 22. }
 23> ["a": 1, "b": 2].toJSONString()
$R10: String = "my dictionary"

The Apple documentation does not mention using extensions on Objective-C classes.

This was probably a bug, or incomplete implementation, in the early version you tried in June. It works just fine to extend NSDictionary in latest beta. For example, this very complicated extension and usage works as expected, with code completion:

extension NSDictionary {
    func myFooBar() {
        println("gaaah")
    }
}

// elsewhere...

var d = NSDictionary(object: "bar", forKey: "foo")
d.myFooBar()

In short:

File configuration setup:

CustomClass.h
CustomClass.m
CustomClassExtension.swift

In CustomClassExtension:

@objc extension CustomClass
{
    func method1() 
    {
        ...
    }
}

In any other class:

self.customClass = [[CustomClass alloc] init];
[self.customClass method1];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM