[英]Same extension on multiple swift classes
I have this in my appDelegate and was wondering how to make this into one extension? 我在appDelegate中拥有此功能,想知道如何将其合并为一个扩展?
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
}
}
...
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
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. 如果可以,您应该使用@Mundi的答案,但是如果您希望允许AppDelegate
使用有限数量的结构,则使用以下版本。
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
}
}
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 如果您需要对大多数对象进行某种扩展
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.