Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: How can Objective C code read static variables in Swift?

For Example, say if I have a class like so with a static variable pi.

let pi: Double = 3.1415926

 class MyClass {
// ...
 }

How can I allow Objective C code to use the static variable pi? The projectName-Swift.h class will have auto generated code like so (just a small example and not 100 percent accurate).

  SWIFT_CLASS("_MyClass")
 @interface MyClass : NSObject
 - (instancetype)init OBJC_DESIGNATED_INITIALIZER;
 @end

So pi isn't being added to projectName-Swift.h. This is a small example on what is going on with my project and perhaps it should generate the static variable and I am missing something. Any tips or suggestions to fix this or make this work will be appreciated.

like image 883
William Alex Avatar asked Mar 11 '15 17:03

William Alex


1 Answers

You can't access Swift global variables on Objective C.

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

Using Swift with Cocoa and Objective-C

Check this post too.

like image 138
eduardoeof Avatar answered Dec 01 '22 01:12

eduardoeof