在Objective-C中使用通用的Swift类 [英] Using a generic Swift class in Objective-C
问题描述
class MyArray< T> {
func addObject(object:T){
//做某事...希望
}
}
(我知道有一个稍微更好的数组实现,这仅仅是一个例子。)
在Swift中,我现在可以很容易地使用这个类:
pre $ let a = MyArray< String>()
a.addObject(abc)
使用Xcode 7,我们现在在Objective-C 中有泛型,所以我会假设我可以在Objective-C中使用这个类:
MyArray< NSString *> * a = [[MyArray< NSString *> alloc] init];
[a addObject:@abc];
但是,MyArray永远不会添加到我的 Project-Swift.h中。 code>文件。即使我将它从NSObject继承,它仍然不会出现在我的Swift.h文件中。
有没有什么方法可以创建一个通用的Swift类,然后在Objective-C中使用它?
更新:如果我尝试从NSObject继承使用@objc注释:
@objc(MyArray)
class MyArray< T> ;: NSObject {
func addObject(object:T){
//做某事...希望
}
}
我得到以下编译器错误:
lockquote
'@objc'类的泛型子类不能有明确的'@objc'属性,因为它们不能直接从Objective-C中看到。
这是否意味着无法使用通用Objective-C中的Swift类?
直接在中引入类的方法是什么?
Swift类型不能用于Objective-C。
不包括Swift-only功能,如下面列出的那些:
- 泛型
- ... li>
Let's say I define a generic class in Swift, similar to the following:
class MyArray<T> {
func addObject(object: T) {
// do something... hopefully
}
}
(I know there is a slightly better implementation of array, this is merely an example.)
In Swift I can now use this class very easily:
let a = MyArray<String>()
a.addObject("abc")
With Xcode 7, we now have generics in Objective-C, so I would assume that I could use this class in Objective-C:
MyArray<NSString*> *a = [[MyArray<NSString*> alloc] init];
[a addObject:@"abc"];
However, MyArray is never added to my Project-Swift.h
file. Even if I change it to inherit from NSObject, it still doesn't appear in my Swift.h file.
Is there any way to create a generic Swift class and then use it in Objective-C?
Update: If I try to inherit from NSObject and annotate with @objc:
@objc(MyArray)
class MyArray<T>: NSObject {
func addObject(object: T) {
// do something... hopefully
}
}
I get the following compiler error:
Generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C.
Does this mean there is no way to use a generic Swift class in Objective-C?
How does one indirectly reference the class?
Swift generic types cannot be used in Objective-C.
This excludes Swift-only features such as those listed here:
- Generics
- ...
这篇关于在Objective-C中使用通用的Swift类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!