Swift Learning Daily Tip (6) Single case

Source: Internet
Author: User

近日,在翻看以前写过的一些OC应用的时候,看到了OC的单例,然后暮然想要试着写一写Swift下的单例,于是,在经过一番波折后,终于将Swift下的单例写了出来。
A single example implementation under OC
栗子:+ (instancetype)sharedNetworkTools {    //定义一个任意类型的静态实例    static id instance;    static dispatch_once_t onceToken;    // 第一次进入dispatch_once中,onceToken == 0       // 进入过一次后, onceToken == -1    dispatch_once(&onceToken, ^{        instance = [[self alloc] init];    });    return instance;}

OC under the single case everyone has written memorized, so today I will take you to imitate OC in the way of writing a swift under the single example implementation

Single example under Swift 1. Modeled OC version
//定义一个全局的静态变量static var instance: NetworkTools?//由于在Swift中,闭包内部不能写static函数,所以,只能放在外面实现啦!static var onceToken: dispatch_once_t = 0// 全局的访问点class func sharedNetworkTools() -> NetworkTools {    dispatch_once(&onceToken, { () -> Void in       self.instance = NetworkTools()    })    return instance!}

What do you think? Does it look like OC and its similar? The soup I suggest you can forget the code, according to your idea to write the swift version of the Singleton, you will find that it implies some small pits ~
Below, the small soup I bring to you under swift Special Single example implementation solution ~ Soup I mean love oh ~ Wow Quack!

2.Swift Featured Edition
// 定义一个私有的静态成员private static let instance = NetworkTools()class func sharedNetworkTools() -> NetworkTools {    return instance}

is not good simple!!!
In Swift, it let is thread-safe and, as a constant, is stored in a constant area, and instance = NetworkTools() it is lazy-loaded, and will not run until the first call.
Well, today's knowledge sharing is here ~ Welcome to the small soup blog to put forward valuable suggestions ha ~ attached to the GitHub address Https://github.com/SarielTang, interested in helping a little bit like AH ~

Swift Learning Daily Tip (6) Single case

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.