Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a swift class with a generic type in 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];
like image 960
Morpheus78 Avatar asked Jul 11 '15 21:07

Morpheus78


1 Answers

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

like image 144
Andriy Gordiychuk Avatar answered Sep 22 '22 21:09

Andriy Gordiychuk