swift中单列的写法

来源:互联网 发布:用户体验运营 知乎 编辑:程序博客网 时间:2024/05/23 01:11

swift中单列的写法常见有两种:

1.这种方式较简洁,推荐使用

////  MyManegerOne.swift//  swift_SingleInstance////  Created by MrZhaoCn on 16/12/5.//  Copyright © 2016年 MrZhaoCn. All rights reserved.//  单列写法1,推荐这种,简单import UIKitclass 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.// 单利写法2import UIKitclass MyManegerTwo: NSObject {        class func sharedManager() ->MyManegerTwo {            struct Static {                static let instance : MyManegerTwo = MyManegerTwo()            }            return Static.instance    }}

下面在控制器里面测试一下

////  ViewController.swift//  swift_SingleInstance////  Created by MrZhaoCn on 16/12/5.//  Copyright © 2016年 MrZhaoCn. All rights reserved.//import UIKitclass 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中的单列


0 0
原创粉丝点击