I created this Swift class:
@objc public class Tester: NSObject {
private var name: String
private var user: Users
init(string:String, user: Users) {
print(user.empId)
print(user.name)
self.user = user
self.name = string
super.init()
}
}
I call the initializer from Obj C like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSString * nilString = nil;
Users * nilUser = nil;
Tester * test = [[Tester alloc] initWithString:nilString user:nilUser];
return YES;
}
Here I pass nil
for the parameters to the Swift initializer. Ideally I expect this to crash as the initializer only accepts non-nil
values.
But what actually happens is, when the execution point reaches inside the initializer, new parameter objects are created:
The nil
string becomes ""
and the User
variable that was nil
is now pointing to an object.
But for a property like this
@property(nonatomic,strong) SomeClass * object;
where
object = nil;
When I call this object from swift,
let x = object.someGetter;
This crashes.
At one point, If I pass nil to some non null, it works and at another point, it crashes. Why does this weird behavior exist? If for some reasons, my parameters are nil, and passed to nonnull, I would like this to crash. So that I can fix things.
EDIT: This became so unexpected, further trying to play with this code.
The string parameter was actually as string, but the User shows uninitialized, hence manipulations on string worked well, but the user object, took the changes but did not showed them back.