How to use a swift class with a generic type in objective c

时光怂恿深爱的人放手 提交于 2020-01-14 07:41:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!