Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 250
Olshansk Avatar asked Jun 03 '14 22:06

Olshansk


People also ask

Can Objective-C use Swift?

You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.

Does Objective-C have extensions?

Objective-C source code 'messaging/implementation' program files usually have . m filename extensions, while Objective-C 'header/interface' files have . h extensions, the same as C header files.

Can Swift override extension?

Swift extensions can add new capabilities to a type, but they cannot override anything. You can add completely new functionality with a very similar name to a method, but it cannot be the same and must be unique, and cannot use the override keyword.

Does Apple use Swift or Objective-C?

Most of the core iOS and MacOs software is still written in Objective-C, though Apple is pushing for new updates to be written in Swift.


2 Answers

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];
like image 168
oskarko Avatar answered Oct 06 '22 11:10

oskarko


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.

like image 24
GoZoner Avatar answered Oct 06 '22 10:10

GoZoner