Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional dynamic properties in Swift

I'm attempting to compile the following Swift class:

class Waypoint: NSObject {
    dynamic var coordinate: CLLocationCoordinate2D?
}

But I get the following compiler error:

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

If I change coordinate to be non-optional everything works just fine. I suppose this makes sense, since Objective-C has no concept of optionals. Is there any known solution or workaround?

like image 844
bloudermilk Avatar asked Mar 13 '15 08:03

bloudermilk


1 Answers

In Objective-C, you can use nil to signal the absence of value, but only on object types. Swift generalizes this (and makes it type-safe) with the Optional generic type: you can have an Optional<NSObject>, a.k.a. NSObject?, but you can also have an Int? or a CLLocationCoordinate2D?.

But CLLocationCoordinate2D is a struct — if you use it in Objective-C, you can't assign nil to a variable of type CLLocationCoordinate2D. This is why you get this error.

As for an (ugly) workaround, you could wrap CLLocationCoordinate2D in a object:

class CLLocationCoordinate2DObj: NSObject {
    let val: CLLocationCoordinate2D
    init(_ val: CLLocationCoordinate2D) {
        self.val = val
    }
}

class Waypoint: NSObject {
    dynamic var coordinate: CLLocationCoordinate2DObj?
}

Unfortunately, you can't find a more general solution with a generic object wrapper class for structs, as Objective-C doesn't have generics… An alternative would be to use NSValue as object type as described here, but I doubt that it would be more elegant.

like image 111
Jean-Philippe Pellet Avatar answered Oct 26 '22 06:10

Jean-Philippe Pellet