【发布时间】:2014-07-04 07:17:17
【问题描述】:
我正在尝试将我的一个应用程序从 Objective-C 切换到 swift。快速语言中有些东西我无法开始工作。首先,我有一个Model 类,我在AppDelegate 的didFinishLaunchingWithOptions 中对其进行了初始化。我在 Objective-C 的 .h 文件中声明了 Model 的对象,如下所示:
@property(nonatomic,retain)Model *model;
在didFinishLaunchingWithOptions我初始化它:
self.model=[[Model alloc]init];
然后我有以下方法:
+(Model *)getCurrentModel{
AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
return appdelegate.model;
}
然后我可以通过调用从任何类访问Model 的当前实例:
model = [AppDelegate getCurrentModel];
那么,第一个问题,我如何在 Swift 中做同样的事情?尤其是静态函数(以+ 开头的函数)。我试过这个:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var model : Model?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// Override point for customization after application launch.
model = Model()
return true
}
class var currentModel : Model {
struct Static {
static let instance : Model = AppDelegate.sharedApplication.delegate //error AppDelegate.Type does not have a member named sharedApplication
}
return Static.instance.model
}
第二个问题。在Objective C中,我们可以通过在.h文件中这样声明来创建实例变量和全局变量和全局函数:
@interface ViewController : UIViewController {
//Instance Variables
NSString *aName;
}
//Properties or variables that can be accessed globally
NSString *anotherName;
//Methods that have global scope
- (void)doSomething;
@end
那些未在.h 文件中声明的函数具有本地作用域。我如何在 Swift 中做同样的事情?
【问题讨论】:
-
使用
static关键字声明类函数。 Swift 中没有访问修饰符的概念(至少目前如此)。您声明的所有内容都是公开的。 -
我得到的错误怎么办? sharedApplication?
标签: objective-c scope singleton swift