0

When declaring a variable as dynamic:

dynamic var myProperty: Bool = true 

is there any advantage or change in behavior by also adding the @objc marker?

@objc dynamic var myProperty: Bool = true 

2 Answers 2

1

In Swift 4, dynamic variables will give a compilation error if they do not have the @objc attribute on them. So, you could say the ability to compile is an advantage of adding @objc.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok good to know. The project I’m working on is using Swift 3 and wasn’t noticing any difference. For Swift Versions < 4 is adding @objc completely superfluous (minus an upgrade to Swift 4 if and when it's desired)?
@J2K It seems to. The ObjectiveC runtime is the only one available to Swift, so the only way to achieve dynamic behavior is to also be @objc. dynamic implies @objc, but Swift 4 just makes this explicit.
@J2K At some point, probably not too long from now, Apple will drop support for compiling Swift 3 in Xcode, because Apple. So you should be thinking about converting your code to Swift 4. Having @objc there does not cause any harm in Swift 3, and it makes your life easier when it comes time to update your code. So I would not call it superfluous at all.
0

See Apple's documentation itself. It states

Declarations marked with the dynamic modifier must also be explicitly marked with the @objc attribute unless the @objc attribute is implicitly added by the declaration’s context. For information about when the @objc attribute is implicitly added. See Declaration Attributes

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.