10

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.

William Alex
  • 385
  • 1
  • 3
  • 14
  • Can you use a class method to expose the static variables for your use case? – JRG-Developer Mar 11 '15 at 17:30
  • I will have to modify the Objective c code, but I guess it could work just fine. Also, you mean something like this? class var pi : Double { return 3.1415926 } – William Alex Mar 11 '15 at 17:34
  • You should take a look at http://stackoverflow.com/questions/25918628/how-to-define-static-constant-in-a-class-in-swift This goes down the path suggested by JRG, especially Martin's answer – Peter M Mar 11 '15 at 18:11

3 Answers3

29

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.

Community
  • 1
  • 1
eduardoeof
  • 399
  • 2
  • 6
  • 1
    (xCode 7.3.1) Looks like that `@objc` is not needed anymore. Also, a root class can't be accessed from Objective-C, you have to inherit `NSObject` – Axel Guilmin Aug 29 '16 at 15:48
1

You also need to indicate that they are public

@objc public class MyClass { 
    @objc public static let pi = 3.14
}
Booharin
  • 753
  • 10
  • 10
0

I would make pi static and put it inside MyClass. Also add @objc infront of each of them like this.

@objc class MyClass { 
    @objc static let pi = 3.14
}

Then in your objective C code you can call it like this

CGFloat piValue = MyClass.pi;
candyline
  • 788
  • 8
  • 17