Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift globals and global functions in objective c

the documentation says:

Global constants defined in C and Objective-C source files are automatically imported by the Swift compiler as Swift global constants.

But it doesn't say anything about the other way around. I need to define a global swift constant and be able to see it one the objective c side like a global c constant. Like on the swift side define:

public let CARDS = ["card1", "card2"] 

and see use it on the objective c side like

NSLog(@"Cards count: %d", [CARDS count]) 

What should I do? I've already imported the swift automatically generated header like:

#import "MyProject-Swift.h" 

and in Xcode if I command-click on it, it takes me to the correct place in the swift code, but at compile time I get:

'User of undeclared Identifier CARDS' 

on my objective c side.

like image 364
Ali Avatar asked Oct 20 '14 10:10

Ali


People also ask

What are global functions in Swift?

Swift. Global functions, or functions that can be accessed from anywhere without the scope of a specific type is an old concept that was popular in languages like C and Objective-C, but unrecommended in Swift as we would rather have things that are nicely typed and scoped ("swifty").

How do you declare a global variable in Objective C?

int gMoveNumber = 0; at the beginning of your program—outside any method, class definition, or function—its value can be referenced from anywhere in that module. In such a case, we say that gMoveNumber is defined as a global variable.

Are global functions closures in Swift?

Global functions are closures that have a name and don't capture any values. Nested functions are closures that have a name and can capture values from their enclosing function.


1 Answers

Here is the document about it

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

Global variables (including constants) are unaccessible from Objective-C.

Instead, you have to declare a class which has accessors for the global constants.

// Swift public let CARDS = ["card1", "card2"]  @objc class AppConstant {    private init() {}    class func cards() -> [String] { return CARDS } }  // Objective-C NSArray *cards = [AppConstant cards]; 
like image 104
rintaro Avatar answered Sep 16 '22 17:09

rintaro