问题
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];
回答1:
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
来源:https://stackoverflow.com/questions/31361848/how-to-use-a-swift-class-with-a-generic-type-in-objective-c