1

I have this in my appDelegate and was wondering how to make this into one extension?

extension UIViewController {
    var appDelegate:AppDelegate {
        return UIApplication.sharedApplication().delegate as! AppDelegate
    }
}

extension Blue {
    var appDelegate:AppDelegate {
        return UIApplication.sharedApplication().delegate as! AppDelegate
    }
}

extension Green {
    var appDelegate:AppDelegate {
        return UIApplication.sharedApplication().delegate as! AppDelegate
    }
}
...
Gert Cuykens
  • 6,845
  • 13
  • 50
  • 84
  • 2
    @Mundi's answer is definitely the right approach, but if you think you require this, you almost certainly have a design mistake and have put too much information into your Application Delegate. The only part of the system that should know about the Application Delegate is the (UI)Application. The Application Delegate is not a place to hold global state. http://stackoverflow.com/questions/9213134/is-it-ok-to-place-most-logic-and-models-in-the-appdelegate/9213624#9213624 See also http://stackoverflow.com/questions/8421138/importing-appdelegate – Rob Napier Dec 22 '15 at 19:22

3 Answers3

4

You should use @Mundi's answer if you can, but here is version if you would want to allow AppDelegate to limited number of structures.

You can make a protocol and add this variable to everyone conforming to this protocol:

protocol AppDelegatable {
    var appDelegate: AppDelegate { get }
}

extension AppDelegatable {
    var appDelegate: AppDelegate {
        return UIApplication.sharedApplication().delegate as! AppDelegate
    }
}
sunshinejr
  • 4,834
  • 2
  • 22
  • 32
  • Correct. It seems to me that there is some code that will have to be added to a lot of classes, though. Makes sense if you want to limit access to the app delegate for a good reason. – Mundi Dec 22 '15 at 19:20
  • Yeah, same, just saw your answer and thought that it could be helpful for him anyways :) – sunshinejr Dec 22 '15 at 19:21
  • `appdelegate` aside I found it the most suitable answer for `Same extension on multiple swift classes` but in case of `appdelegate` @Mundi is probably right. – Gert Cuykens Dec 22 '15 at 19:40
2

You just want to make your app delegate available, which is sensible in most contexts. I recommend the convenience of a global variable (write this above your app delegate class):

let SharedAppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
Mundi
  • 79,884
  • 17
  • 117
  • 140
1

You could always do:

extension NSObject
{
    var appDelegate:AppDelegate {
        return UIApplication.sharedApplication().delegate as! AppDelegate
    }
}

if you need any kind of extension to be carried out to most of your objects

Knight0fDragon
  • 16,609
  • 2
  • 23
  • 44