Search code examples
objective-cswift2cgimage

Swift 2 - Convert objective-c #define to swift


I am trying to convert a project from objective-c to swift. I have some problems converting #define over swift.

what I have is:

    #define Mask8(x) ( (x) & 0xFF )
    #define R(x) ( Mask8(x) )
    #define G(x) ( Mask8(x >> 8 ) )
    #define B(x) ( Mask8(x >> 16) )

UInt32 color = *currentPixel;
      printf("%3.0f ", (R(color)+G(color)+B(color))/3.0);

How can I convert this to variable in swift?


Solution

  • The 4 #defines in your question are not made available to Swift, see the section titled Complex Macros at https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html

    If you want to have their equivalents available in Swift, you will need to re-implement them in Swift. A simple approach, assuming the macro parameter is of type UInt32 as it is in your example, might be as follows:

    func swiftMask8(x:UInt32) -> UInt32
    {
        return x & 0xFF
    }
    
    func swiftR(x:UInt32)->UInt32
    {
        return swiftMask8(x)
    }
    ...
    

    Of course, you can drop the swift part and just call the functions Mask8, 'R`, etc., since their Objective-C equivalents are not visible to Swift anyway.