I've read a few articles about it and understand the basic principle and do agree that it could be useful in some cases. However, most of the time I would want my program to crash if I was getting nil
somewhere that I shouldn't be -- that's how'd I know there was a problem!
Furthermore I've read that using optionals can lead to shorter code.. How is that possible?? From what I've seen the whole idea behind them is they can either have a value or nil
so you have to do additional checking whereas previously that wasn't necessary!
And what's up with needing to use "as" all the time? It just makes everything more verbose and lengthy. For example, compare the following code in Objective-C and Swift
Objective-C:
UIViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"Home"];
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
appDelegate.window.rootViewController = vc;
[UIView transitionWithView:appDelegate.window
duration:0.2
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{ appDelegate.window.rootViewController = vc; }
completion:nil];
Swift:
//have to check if self.storyboard != nil
let viewController:UIViewController = self.storyboard?.instantiateViewControllerWithIdentifier("Home") as UIViewController; //Isn't the view controller returned by instantiateViewControllerWithIdentifier() already of type UIViewController?
let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate; //Isn't the delegate returned by sharedApplication() already of type AppDelegate?
//have to check if appDelegate.window != nil
appDelegate.window!.rootViewController = viewController as UIViewController; //Why cast viewController as UIViewController if the type has already been explicitly set above?
UIView.transitionWithView(
appDelegate.window!,
duration: 0.2,
options: UIViewAnimationOptions.TransitionCrossDissolve,
animations:{appDelegate.window!.rootViewController = viewController as UIViewController},
completion: nil
);
Am I doing something wrong? Or is this really the way that it was intended to be?