全局变量在 Swift 中的实现

目标

通过 Swift 实现一个全局变量(类的实例对象),在 App 整个生命周期内有且只有一个该变量,实质就是设计模式中的单例模式(SingleTon)。

实现

新建文件 Constant.swift,实现类的定义:

import UIKit

class GlobalConstants: NSObject {
    static let shared: GlobalConstants = GlobalConstants()
    var name = "wangmingjun.com"
    var age = 50
}

在 Swift 中全局变量默认使用的是懒加载(延迟加载)方式,即第一次引用时才会初始化。若需要该全局变量尽早生效,建议使用如下方式:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    print(GlobalConstants.shared)
    GlobalConstants.shared.age = 51
    return true
}

在 VC 中引用或者设置全局变量的值:

/* Writing in first view: Set age to 51: */
GlobalConstants.shared.age = 51

/* Reading in second view: Get age of 51 */
let age = GlobalConstants.shared.age

参考资料

  1. What Is a Singleton and How To Create One In Swift
  2. xcode – Creating a global variable in swift – Stack Overflow
  3. How to define global constant in swift? – iOSDevCenter
  4. 设计模式总结篇系列:单例模式(SingleTon) – Windstep – 博客园

 

Advertisements

分类:iOS

Tagged as: , , ,

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google+ photo

You are commenting using your Google+ account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s

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