简体   繁体   English

从 Objective-C 访问 Swift 扩展

[英]Accessing Swift Extension From Objective-C

I'm having trouble accessing my swift extension from objective-c.我无法从 Objective-c 访问我的 swift 扩展。

I have the following code in a .swift file:我在 .swift 文件中有以下代码:

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:我希望能够在我的 .m 文件中执行以下操作:

[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.我知道我的导入工作正常,因为我能够访问我的其他 swift 对象。

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. Apple 文档没有提到在 Objective-C 类上使用扩展。

This was probably a bug, or incomplete implementation, in the early version you tried in June.这可能是您在 6 月份尝试的早期版本中的错误或不完整的实现。 It works just fine to extend NSDictionary in latest beta.在最新的测试版中扩展 NSDictionary 效果很好。 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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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