Search code examples
iosswiftmacrosios8

Swift + macro parameters


I read all Q&A related to Macros in Swift, And i did figure out that everything in Swift now global, Am i right?

And my actual question is that if i have a macro in which i need parameters to be pass then how can i pass it in Swift language?

e.g.

Objective-C Macro

#define COLOR_CODE(red, green, blue, alpha) [UIColor colorWithRed: red/255.0 green: green/255.0 blue: blue/255.0 alpha: alpha]

What is the Swift syntax for above macro?


Solution

  • As 0O0O0O0 mentioned, macros in the sense of "The compiler should see COLOR_CODE(0, 0, 0, 1) and replace it with [UIColor colorWithRed: 0/255.0 green: 0/255.0 blue: 0/255.0 alpha: 1]" do not exist in Swift.

    Macros in C can be used in ways that produce confusing error messages:

    #define IS_EQUAL_TO_ME(argument) [self isEqual: argument]
    
    BOOL func(id argument) {
        return IS_EQUAL_TO_ME(argument);
    }
    
    // Error: Use of undeclared identifier 'self'
    

    Or destroy readability:

    #define OPEN_BLOCK {
    #define CLOSE_WITH_EXIT_IF_FALSE } else { exit (0); }
    
    if (x < 0)
    OPEN_BLOCK
        return 10;
    CLOSE_WITH_EXIT_IF_FALSE
    

    For simple cases like COLOR_CODE a commonly recommended strategy for C was to use inline functions:

    NS_INLINE UIColor *ColorCode(CGFloat r, CGFloat g, CGFloat b, CGFloat a) {
        return [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a];
    }
    

    This had the same performance as the macro in that it would get inlined to the same code but is strongly typed and does not depend on macro processing rules. This code also has a direct translation to Swift:

    func ColorCode(red:CGFloat, green:CGFloat, blue:CGFloat, alpha:CGFloat) -> UIColor {
        return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: alpha)
    }
    

    Because "everything is global" you can declare this in any file and use it in any other file in the same module. It is up to the compiler in this case to decide whether or not to inline the function.