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对象。
2 个解决方案
#1
0
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类上使用扩展。
#2
1
This was probably a bug, or incomplete implementation, in the early version you tried in June. It works just fine to extend NSDictionary in latest beta. For example, this very complicated extension and usage works as expected, with code completion:
这可能是您在6月份尝试的早期版本中的错误或不完整的实现。它可以在最新的测试版中扩展NSDictionary。例如,这个非常复杂的扩展和使用按预期工作,代码完成:
extension NSDictionary {
func myFooBar() {
println("gaaah")
}
}
// elsewhere...
var d = NSDictionary(object: "bar", forKey: "foo")
d.myFooBar()
#1
0
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类上使用扩展。
#2
1
This was probably a bug, or incomplete implementation, in the early version you tried in June. It works just fine to extend NSDictionary in latest beta. For example, this very complicated extension and usage works as expected, with code completion:
这可能是您在6月份尝试的早期版本中的错误或不完整的实现。它可以在最新的测试版中扩展NSDictionary。例如,这个非常复杂的扩展和使用按预期工作,代码完成:
extension NSDictionary {
func myFooBar() {
println("gaaah")
}
}
// elsewhere...
var d = NSDictionary(object: "bar", forKey: "foo")
d.myFooBar()