Property cannot be marked @objc because its type cannot be represented in Objective-C

i0S Swift Issue

Question or problem in the Swift programming language:

I’m finishing a port for a project that was written in Swift to support Objective-C. A lot of the project was written to support Objective-C but not the properties on a particular class.

This is the property:

open var remainingTime: ( hours: Int, minutes: Int, seconds: Int)?

I’m guessing I can’t just add @objc to this because “hours”,”minutes”,”seconds” are objects. How do I make this property visible to my Objective-C project?

How to solve the problem:

Solution 1:

You can create a class that represents your tuple.


class Time: NSObject {
    let hours: Int
    let minutes: Int
    let seconds: Int

    init(hours: Int, minutes: Int, seconds: Int) {
        self.hours = hours
        self.minutes = minutes
        self.seconds = seconds

@objc open var remainingTime: Time?

Solution 2:

This error occurred in project when I tried to observe an Enum via KVO. My enum looked like this:

enum EnumName: String {
    case one = "One"
    case two = "Two"

In case you are struggling to observe it, this workaround helped solve my issue.

Observable Class:
  • create @objc dynamic var observable: String?
  • create your enum instance like this:

    private var _enumName: EnumName? { didSet { observable = _enumName!.rawValue } } 
Observer Class:
  • create private var _enumName: EnumName?
  • create private let _instance = ObservableClass()
  • create

    private var _enumObserver: NSKeyValueObservation = _instance.observe(\.observable, options: .new, changeHandler: { [weak self] (_, value) in guard let newValue = value.newValue else { return } self?._enumName = EnumName(rawValue: period)! }) 

Than’s it. Now each time you change the _enumName in the observable class, an appropriate instance on the observer class will be immediately updated as well.

This is of course an oversimplified implementation, but it should give you an idea of how to observe KVO-incompatible properties.

Hope this helps!