如何在swift中安全的聲明一個(gè)單例?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。
Talk is cheap. Show me the code.
class TestShareInstance{ var age:Int static let shareInstane:TestShareInstance = TestShareInstance(age: 3); private init(age:Int){ self.age = age; }; }
swift在類中,類變量是能夠保證線程安全,swift底層,static關(guān)鍵字的實(shí)際上是使用dispatch_once語法來實(shí)現(xiàn)的,如下一段swift編譯中間產(chǎn)物SIL語言中的代碼就能看到底層的實(shí)現(xiàn).
1.staic變量被聲明為全局變量
// static TestShareInstance.shareInstane sil_global hidden [let] @static main.TestShareInstance.shareInstane : main.TestShareInstance : $TestShareInstance
2.在get方法中獲取變量調(diào)用了swift內(nèi)嵌的builtin "once",實(shí)際上調(diào)用的是swift_once方法
3.在swift源碼中可以搜索到swift_once方法的內(nèi)部實(shí)現(xiàn)如下,內(nèi)部調(diào)用的就是GCD底層的dispatch_once_f,保證了單例的線程安全。
/// Runs the given function with the given context argument exactly once. /// The predicate argument must point to a global or static variable of static /// extent of type swift_once_t. void swift::swift_once(swift_once_t *predicate, void (*fn)(void *), void *context) { #if defined(__APPLE__) dispatch_once_f(predicate, context, fn); #elif defined(__CYGWIN__) _swift_once_f(predicate, context, fn); #else std::call_once(*predicate, [fn, context]() { fn(context); }); #endif }
在類中,將TestShareInstance的init方法設(shè)置為了private,這能保證其他人沒有辦法調(diào)用你的init的方法,只能調(diào)用你的shareInstane單例變量;從而保證了單例的不可修改特性。如果你要強(qiáng)行修改,編譯器就會(huì)警告你,具體示例如下
關(guān)于如何在swift中安全的聲明一個(gè)單例問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。