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