2

I am stuck in converting #define and weak from objective c to swift. I tried to use objective c to swift convertor, but I think the result of conversion is not correct.

#define WeakRef(__obj) __weak typeof(self) __obj = self
#define WeakReturn(__obj) if(__obj ==nil)return;
WeakRef(weakSelf);
WeakReturn(weakSelf);

For the second, third and forth lines, I think it should be something like this in Swift

func WeakReturn(obj: Any?) {
    if obj == nil {
        return
    }
}
WeakRef(self)
WeakReturn(self)

In my guess for the first line, it first check the condition of typeof(self) == ??. If true, then set the pointer (__obj) to self. But, I am not sure about what ?? should be.

Pak Ho Cheung
  • 1,382
  • 6
  • 22
  • 52

1 Answers1

2

WeakRef simply gives you a weak reference to some object, and in Swift, that's just weak var foo = obj; it doesn't need a utility method.

WeakReturn can't be replicated in Swift, because the Obj-C macro is used to insert a conditional return in a function. There are no macros in Swift, and the Swift WeakReturn function that you defined does absolutely nothing--it returns whether the object is nil or not; all you've done is make one of those returns explicit. My guess is that this macro was added to the Obj-C code to save some lazy programmer from writing if obj == nil return;.

NRitH
  • 13,441
  • 4
  • 41
  • 44