I am trying to access a Swift class's Double?
property from Objective-C.
class BusinessDetailViewController: UIViewController {
var lat : Double?
var lon : Double?
// Other elements...
}
In another view controller, I am trying to access lat
like following:
#import "i5km-Swift.h"
@interface ViewController ()
@property (strong, nonatomic) BusinessDetailViewController *businessDetailViewController;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.businessDetailViewController = [[BusinessDetailViewController alloc] initWithNibName:@"BusinessDetailViewController" bundle:nil];
self.businessDetailViewController.lat = businessArray[1]; /* THIS GIVES ME AN ERROR */
}
and I am getting
Property 'lat' not found on object of type 'BusinessDetailViewController *'
Why can't I access this property? What am I missing?
Optionals is a swift specific feature, not available in obj-c. Optional class instances work because a nil optional can be mapped to a nil value, but value types (int, floats, etc.) are not reference types, hence variable of those types don't store a reference, but the value itself.
I don't know if there's a solution - a possible workaround is creating non optional properties mapping the
nil
value to an unused data type value (such as -1 when representing an index, or 999999 for a coordinate):That should expose the
_lat
and_lon
properties to obj-c.Note that I have never tried that, so please let us know if it works.
It is, however, possible to "wrap" them in a NSNumber like so :
Optional values of non-Objective-C types aren't bridged into Objective-C. That is, the first three properties of
TestClass
below would be available in Objective-C, but the fourth wouldn't:In your Objective-C code, you'd access those first three properties like this:
In your case, you can either convert
lat
andlong
to be non-Optional or switch them to be instances ofNSNumber
.Note that you need to be careful about your Objective-C code if you take the second approach (switching
lat
andlon
to non-optional properties of typeNSNumber
) -- while the Swift compiler will prevent you from assigningnil
to non-optional properties, the Objective-C compiler has no qualms about allowing it, lettingnil
values sneak into your Swift code with no chance of catching them at runtime. Consider this method onTestClass
:This works fine if invoked with values in both of the properties, but if
nsNumberVar
is set tonil
from the Objective-C code, this will crash at runtime. Note that there is no way to check whether or notnsNumberVar
isnil
before using it!If your property is a Swift protocol type, just add
@objc
in front of it.Example: