Accessing AppDelegate in swift 1…3

We all learned in college that global variables are undesirable, but most iOS applications need to access some global members of the shared UIApplication object.

We all learned in college that global variables are undesirable, but most iOS applications need to access some global members of the shared UIApplication object.

I appreciate that the Swift syntax is getting better and better, but it’s still a moving target and challenges my noodle to keep up.

Here’s a quick cheat sheet on accessing AppDelegate through the versions. In each example, we’re getting our shared appDelegate to check a variable called isProduction

Swift 3

let appDelegate = UIApplication.shared.delegate as! AppDelegate let isProd = appDelegate.isProduction

Swift 1.2–2.0

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let isProd = appDelegate.isProduction

Swift 0..<1.2

let appDelegate = UIApplication.sharedApplication as AppDelegate let isProd = appDelegate.isProduction

Author: Rob Kerr

Consultant and expert in software development for the iOS and Android platforms. Microsoft MVP Alumnus.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.