在Swift中實現單例方法

來源:互聯網
上載者:User

標籤:

在寫Swift的單例方法之前可以溫習一下Objective-C中單例的寫法:

1 + (instancetype)sharedSingleton{2     static id instance;3     4     static dispatch_once_t onceToken;5     dispatch_once(&onceToken, ^{6         instance = [[self alloc] init];7     });8     return instance;9 }

首先可以考慮仿照OC中的寫法寫一個。

因此Swift中的一種寫法可以如下:

 1 class Singleton: NSObject { 2  3     static var instance: Singleton? 4     static var onceToken: dispatch_once_t = 0 5      6     //仿照OC中的寫法 7     class func sharedSingleton() ->Singleton { 8         dispatch_once_(&onceToken) { () -> Void in 9             instance = Singleton()10     11         }12         return instance!13     }14 }

 

Swift在OC基礎之上做了很多最佳化提升,因此可以考慮利用Swift的一些新的特性來實現單例。

考慮到Swift中let本身就是安全執行緒的,因此在Swift中實現單例可以非常簡練:

static let sharedSingleton = Singleton()

由於實現方式已經從原來的函數變成了屬性,因此在使用時也需要做相應的調整,使用時如下:

Singleton.sharedSingleton

由此可見,在最佳化吸收多種語言優點之後出現的Swift,在實現單例上相比以往有了很大程度的精簡。

在Swift中實現單例方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.