15

I'm trying to observe Bool value in swift using KVO and add dynamic modifier like this :

dynamic var isRestricted:Bool?

and the compiler say

Property cannot be marked dynamic because its type canot be represented in Objective-C

then what should I do? should I change to NSNumber for this? and What is the best practice for observing value then?

im using xcode 7 beta 2

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Dennis Farandy
  • 277
  • 1
  • 5
  • 9

1 Answers1

44

The actual problem is that optional booleans cannot be represented in Objective-C (and therefore not marked dynamic). Using a non-optional

dynamic var isRestricted : Bool = false

should solve the problem.

Generally, the concept of "optionals" does not exist in Objective-C, but optional references to instances of NSObject subclasses are bridged to nullable object pointers in Objective-C, so

dynamic var foo: Foo?

is allowed if (and only) if Foo is a subclass of NSObject.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 2
    It is partially correct. You **can** have optional properties marked as dynamic, but not booleans nor integers. For example you could have ``dynamic var myObject : MyClass?`` – vomi Feb 18 '17 at 09:47
  • 1
    @vomi: You are completely right, thanks for the feedback. I hope that it is correct now. – Martin R Feb 18 '17 at 12:06