Ios 从Objective-C访问Swift扩展
我无法从objective-c访问我的swift分机 我在.swift文件中有以下代码:Ios 从Objective-C访问Swift扩展,ios,objective-c,swift,swift-extensions,Ios,Objective C,Swift,Swift Extensions,我无法从objective-c访问我的swift分机 我在.swift文件中有以下代码: extension NSDictionary { func dictionaryAsJsonString() -> NSString { var err: NSError? var data = NSJSONSerialization.dataWithJSONObject(self, options: NSJSONWritingOptions.PrettyPri
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对象。只需使用一本字典就足够了
20> extension Dictionary {
21. func toJSONString () -> String { return "my dictionary" }
22. }
23> ["a": 1, "b": 2].toJSONString()
$R10: String = "my dictionary"
苹果的文档没有提到在Objective-C类上使用扩展。这可能是您在6月份尝试的早期版本中的一个bug,或者是不完整的实现。在最新的测试版中扩展NSDictionary效果很好。例如,这个非常复杂的扩展和使用按照预期工作,代码完成:
extension NSDictionary {
func myFooBar() {
println("gaaah")
}
}
// elsewhere...
var d = NSDictionary(object: "bar", forKey: "foo")
d.myFooBar()
简言之:
文件配置设置:
CustomClass.h
CustomClass.m
CustomClassExtension.swift
在CustomClassExtension中:
@objc extension CustomClass
{
func method1()
{
...
}
}
在任何其他类别中:
self.customClass = [[CustomClass alloc] init];
[self.customClass method1];
在文档中,他们提到了扩展如何类似于类别(这是可以通过这种方式实现的)。虽然我还没有尝试过,但我假设如果我在现有的obj-c类上有一个类别,我将能够通过swift访问这些方法。但是根据你所说的,它不会以另一种方式工作?从XCode版本7.1.1(7B1005)开始,在objective c中的其他部分似乎不起作用。你知道如何从objective-c调用扩展吗