Swift中单例的写法常见有两种:
1.这种方式较简洁,推荐使用
//
// MyManegerOne.swift
// swift_SingleInstance
//
// Created by MrZhaoCn on 16/12/5.
// Copyright © 2016年 MrZhaoCn. All rights reserved.
// 单例写法1,推荐这种,简单
import UIKit
class MyManegerOne: NSObject {
private static let shareInstance = MyManegerOne()
class func shareManeger() ->MyManegerOne {
return shareInstance
}
}
2.这种方式也可以,相比于第一种推荐前者
//
// MyManegerTwo.swift
// swift_SingleInstance
//
// Created by MrZhaoCn on 16/12/5.
// Copyright © 2016年 MrZhaoCn. All rights reserved.
// 单例写法2
import UIKit
class MyManegerTwo: NSObject {
class func sharedManager() ->MyManegerTwo {
struct Static {
static let instance : MyManegerTwo = MyManegerTwo()
}
return Static.instance
}
}
下面在控制器里面测试一下
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let myManeger = MyManegerOne.shareManeger()
print(myManeger)
let myManeger1 = MyManegerOne.shareManeger()
print(myManeger1)
let myManegerTwo = MyManegerTwo.sharedManager()
print(myManegerTwo)
let myManegerTwo1 = MyManegerTwo.sharedManager()
print(myManegerTwo1)
}
}
打印结果:可以看出正确的实现了swift中的单例: