【问题标题】:Accessing Swift Extension From Objective-C从 Objective-C 访问 Swift 扩展
【发布时间】:2014-06-03 22:55:09
【问题描述】:

我在从 Objective-c 访问我的 swift 扩展时遇到问题。

我在 .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
    }
}

我希望能够在我的 .m 文件中执行以下操作:

[dictionary dictionaryAsJsonString];

但它找不到我的方法并且不会自动完成。

我知道我的导入工作正常,因为我能够访问我的其他 swift 对象。

【问题讨论】:

  • 你知道如何从 Objective-C 调用扩展

标签: ios objective-c swift swift-extensions


【解决方案1】:

使用字典就很简单

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

Apple 文档没有提到在 Objective-C 类上使用扩展。

【讨论】:

  • 在文档中,他们提到了扩展是如何类似于类别的(你可以这样做)。虽然我还没有尝试过,但我假设如果我在现有的 obj-c 类上有一个类别,我将能够通过 swift 访问这些方法。但是按照你说的,反过来不行?
【解决方案2】:

这可能是您在 6 月份尝试的早期版本中的一个错误或不完整的实现。在最新的测试版中扩展 NSDictionary 效果很好。例如,这个非常复杂的扩展和使用按预期工作,代码完成:

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

// elsewhere...

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

【讨论】:

  • 从 XCode 版本 7.1.1 (7B1005) 开始执行目标 c 中的其他部分似乎不起作用。
【解决方案3】:

简而言之:

文件配置设置:

CustomClass.h
CustomClass.m
CustomClassExtension.swift

在自定义类扩展中:

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

在任何其他类别中:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    相关资源
    最近更新 更多