Implementing a singleton approach in Swift

Source: Internet
Author: User

Before you write Swift's Singleton method, you can review the objective-c of the single example:

 1  + (Instancetype) sharedsingleton{  2  static  id   instance;  3   Static   dispatch_once_t Oncetoken;  5  dispatch_once (&oncetoken, ^{ Span style= "color: #008080;" >6  instance = [[Self alloc] init];  7  });  8  return   instance;  9 } 

The first thing to consider is to follow the notation in OC to write one.

So one way to do this in Swift is as follows:

1 classSingleton:nsobject {2 3     Staticvar Instance:singleton?4     Staticvar oncetoken:dispatch_once_t =05     6     //Follow the notation in OC7     classFunc Sharedsingleton ()Singleton {8Dispatch_once_ (&oncetoken) {() Voidinch9Instance =Singleton ()Ten      One         } A         returninstance! -     } -}

Swift has done a lot of optimization on the OC Foundation, so consider using some of the new features of Swift to implement the singleton.

Given that the let in Swift itself is thread-safe, implementing a singleton in Swift can be very concise:

static Let Sharedsingleton = Singleton ()

Since the implementation has changed from the original function to a property, so the use of the corresponding adjustments need to be made, when used as follows:

Singleton.sharedsingleton

Thus, Swift, which has been optimized to absorb the advantages of multiple languages, has been largely streamlined compared to the previous one.

Implementing a singleton approach in Swift

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.