如何在目标c中使用具有泛型类型的Swift类 [英] How to use a swift class with a generic type in objective c
问题描述
我有一个NumericType T的swift类。
@objc class MathStatistics< T:NumericType> :NSObject {
var numbers = [T]()
func sum() - > T' {
if numbers.count == 0 {
return nil
}
var sum = T(0)
数字{
sum = sum + value
}
返回金额
}
}
在swift中,初始化类对象如下:
let statistics = MathStatistics< Double>()
如何在Objective C中初始化同一个对象?
以下行不设置数字类型T。
MathStatistics * stats = [[MathStatistics alloc] init] ;
你不能。如文档:
您可以访问类别或协议中的任何内容,即
用@objc属性标记,只要它与
Objective-C兼容即可。这不包括Swift-only特性,例如这里列出的
:
$ b
- 泛型
- 元组
- 在Swift中定义的枚举
- 在Swift中定义的结构
- 在Swift中定义的顶级函数
- Swift中定义的全局变量
- Swift中定义的类型别
- Swift风格的变量
- 嵌套类型
- 咖喱函数
<你必须摆脱你班级的泛型。然后你可以在Objective-C
中使用它
I have the following swift class with a NumericType T.
@objc class MathStatistics<T: NumericType> : NSObject {
var numbers = [T]()
func sum() -> T? {
if numbers.count == 0 {
return nil
}
var sum = T(0)
for value in numbers {
sum = sum + value
}
return sum
}
}
In swift a initialize the class object as follows:
let statistics = MathStatistics<Double>()
How do I initialize the same object in Objective C? The following line does not set the numeric type T.
MathStatistics *stats = [[MathStatistics alloc] init];
You can't. As listed in the documentation:
You’ll have access to anything within a class or protocol that’s marked with the @objc attribute as long as it’s compatible with Objective-C. This excludes Swift-only features such as those listed here:
- Generics
- Tuples
- Enumerations defined in Swift
- Structures defined in Swift
- Top-level functions defined in Swift
- Global variables defined in Swift
- Typealiases defined in Swift
- Swift-style variadics
- Nested types
- Curried functions
You'd have to get rid of generics in your class. Then you can use it in Objective-C
这篇关于如何在目标c中使用具有泛型类型的Swift类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!