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.
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.
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.
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.
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.
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With