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.