Search code examples
iosswiftrealm

Realm forces to add @objc word while defining dynamic variables


I am currently playing around with RealmSwift and in the tutorial of Marin Todorov, he created variables like this and compiler doesn't complain.realm tutorial image

But whenever I try to create those variables by myself, compiler wants me to add @objc wordcompiler error

Are those different things or do they behave differently?


Solution

  • That tutorial is written in September 2016, which is quite outdated.

    It used to be that if you have a class that is exposed to Objective-C, then all its members are exposed to Objective-C. In Swift 4, things that are not marked with @objc are not exposed to Objective-C, regardless of whether it is a member of a @objc class.

    Realm needs to do dynamic stuff on your properties, like KVO. That's why dynamic is needed. But dynamic is a feature exclusive to stuff that is exposed to Objective-C, which is why you need @objc.

    This is also why Realm can't handle Swift optionals, because they can't be bridged to Objective-C. You have to use RealmOptional<T>.

    In short, just add @objc to your properties and everything will be fine.