Three ways Swift defines a single case

Source: Internet
Author: User

The first type: Use GCD. Customize a class to inherit the classes you want to inherit, define a static optional variable, declare a dispatch_once_t, and assign an initial value of 0 (0 means it has not been instantiated, if the instance is over its value is always 1), the remainder is similar to the OC definition Singleton

1 classNetworktools:afhttpsessionmanager {2 3     //MARK:-Single case4     Staticvar instance:networktools?5     Staticvar once_t:dispatch_once_t =06     7     classFunc shareinstance ()Networktools8     {9Dispatch_once (&once_t) { Ten              OneInstance =Networktools () A         } -          -         returninstance! the     } -}

The second kind: directly define a static immutable constant, and then define a class method return value for the class you want to Singleton, return this variable directly

1     static Let Networktool = networktools ()2     3     class func Shareinstance () networktools {45         return  networktool  6     }

Third: Similar to the second one, except that defining constants is directly implemented in a lazy-loading manner

1 StaticLet Networktool:networktools = {2        3Let Networktool = Networktools (BaseURL:NSURL.init (string:"https://api.weibo.com/"))4         5NetworkTool.responseSerializer.acceptableContentTypes = (Nsset (objects:"Application/json","Text/json","Text/javascript","Text/plain") as! Set<string>)6 7         returnNetworktool8     }()9     Ten     classFunc shareinstance ()Networktools One     { A         returnNetworktool -}

Three ways Swift defines a single case

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.