Hashem Aboonajmi Hashem Aboonajmi - 1 year ago 182
Objective-C Question

Convert complex Objective-C macros to swift

I've used a library named LinqToObjectiveC in my project and now I want to use it in swift files. this library uses complex objective-C macros which are not accessible in swift. I want to know how can I convert for example this macro to swift:

#define LINQKey(__key) (^id(id item){return [item valueForKey:@#__key];})

Answer Source

First let's explain what that macro is doing.

It takes an argument called __key, stringifies it (@ and #) and returns a closure (block) that will take an object as an parameter and returns the result of item.valueForKey(key).

We can't convert stringification to Swift, however, that's something that shouldn't be used even in Obj-C. Why should we have LINQKey(myKey) when we can have LINQKey(@"myKey")?

As a simple function that returns a closure:

func LINQKey(key: String) -> (AnyObject! -> AnyObject!) {
    return { (item: AnyObject!) in
        return item.valueForKey(key)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download