首先创建一个新的快捷文件
import Foundation
//创建一个单例类
//如果一个类始终只能创建一个实例,则这个类被称为单例类
class Singleton{
// 给类添加一个属性
var action = "Run"
// 对于单例实例来说,需要创建一个唯一对外输出实例的方法
// 静态变量用static来处理
static let singleton = Singleton()
// 创建一个方法,输出实例自身的属性
func doSomething() {
print(action)
}
}
在视图控制器文件中使用该实例
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// 创建两个常量,用来表示同一个单例类的实例
let singleton1 = Singleton.singleton
let singleton2 = Singleton.singleton
// 观察输出结果
singleton1.doSomething()
// 更该第二个单例对象的属性值
singleton2.action = "Walk"
singleton2.doSomething()
singleton1.doSomething()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}