回顾 Objc 创建单例的方式:
@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.创建单例
class TheOneAndOnlyKraken {
// 单例传送的值
var userName:String?
// 定义类方法 +
static let sharedInstance = TheOneAndOnlyKraken()
/// 设置 init 方法私有。防止调用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")
单例是全局唯一的。只初始化一次。且必须保证线程安全。所以单例类的初始化方法必须是私有的。这样就可以避免其他对象通过单例类创建额外的实例
网友评论