ios – Creating Objectiv-C object with custom init in Swift results in Optional – Why?


Because the initialization method provided by the CocoaTouch frameworks can never be return nil value。However, custom initializers method can return nil value。
for example

// SomeViewController.h

@interface SomeViewController : UIViewController { }
- (id)initWithData:(MyData *)data;
@end

// SomeViewController.m
@implementation SomeViewController { }

- (id)initWithData:(MyData *)data {
    return nil;
}

@end

or overwrite init method

@interface SomeViewController : UIViewController { }
- (id)init;
@end

// SomeViewController.m
@implementation SomeViewController { }

- (id)init {
    return nil;
}

@end

Xcode BUG

func foo() -> UIViewController {
    // returns nil will be crash!!!
    // Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
    return SomeViewController(data: someData)   // unsafe
}

error message

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img