回顧 Objc 創(chuàng)建單例的方式:
@interface Kraken : NSObject
@end
@implementation Kraken
+ (instancetype)sharedInstance {
static Kraken *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[Kraken alloc] init];
});
return sharedInstance;
}
@end
1.創(chuàng)建單例
class TheOneAndOnlyKraken {
// 單例傳送的值
var userName:String?
// 定義類方法 +
static let sharedInstance = TheOneAndOnlyKraken()
/// 設(shè)置 init 方法私有十绑。防止調(diào)用init 方法 破壞類的單一性
private init() {} //This prevents others from using the default '()' initializer for this class.
}
2.給單例的屬性賦值
let the = TheOneAndOnlyKraken.sharedInstance
the.userName = "xxx"
3.輸出單例的屬性值
let the = TheOneAndOnlyKraken.sharedInstance
print(the.userName ?? "default value")
單例是全局唯一的。只初始化一次。且必須保證線程安全捐寥。所以單例類的初始化方法必須是私有的。這樣就可以避免其他對(duì)象通過單例類創(chuàng)建額外的實(shí)例