5

I have define #define baseUrl [NSString stringWithFormat:@"%@api/v4", MAINURL] in objective c class and can access anywhere in project. But now i have created swift file in exiting objective c project and want to access baseurl in swift but error received.

Use of unresolved identifier 'baseUrl'

how can resolve it?

Shahbaz Akram
  • 1,598
  • 3
  • 28
  • 45
  • 1
    Possible duplicate of [How to use a Objective-C #define from Swift](https://stackoverflow.com/questions/24325477/how-to-use-a-objective-c-define-from-swift) – Papershine Jul 04 '18 at 10:05

2 Answers2

9

Importing Objective-C macros into Swift doesn't always work. According to documentation:

Swift automatically imports simple, constant-like macros, declared with the #define directive, as global constants. Macros are imported when they use literals for string, floating-point, or integer values, or use operators like +, -, >, and == between literals or previously defined macros.

C macros that are more complex than simple constant definitions have no counterpart in Swift.

An alternative in your case would be to use a function that returns the value defined by macro

// .h file
#define baseUrl [NSString stringWithFormat:@"%@api/v4", MAINURL]
+ (NSString*) BaseUrl;

// .m file
+ (NSString*) BaseUrl { return baseUrl }
Community
  • 1
  • 1
mag_zbc
  • 6,801
  • 14
  • 40
  • 62
  • How can we manage same #define constant for different schemes ? If we have different targets we are able to add #ifdef (Target_Name) #endif. But if we have only have 1 target and multiple schemes then how to use #if condition ? – Yash Jadhav Mar 15 '23 at 09:43
0

Unfortunately, Objective-C #define could not access by swift.

Maybe you change your #defines to actual constants, which is better than #defines.

Or create a swift object hold some static variable.

For example:

class API: NSObject {
    static let apiPrefix = "https://vvv"
    static let apiPosts = apiPrefix + "posts"
}

Calling: API.apiPosts

Tuesleep
  • 119
  • 13