这是否可以在没有共享实例的情况下制作更短的单身人士? 为什么人们正在创建共享实例var而不是使用这种方式?
简单:
class Singleton {
static var someVar = "Cool it works!"
class func execute() {
print(someVar)
}
Singleton.execute()
Singleton.someVar = "var changed"
Singleton.execute()
// console:
// Cool it works!
// var changed
处理程序:
class Singleton {
static var someVar = "Some Var passed to the handler"
class func execute(handler:(String)->String) {
let varReturnedFromHandler = handler(someVar)
print(varReturnedFromHandler)
}
}
Singleton.execute { (varFromFunction:String) in
print(varFromFunction)
return "Returned var from handler"
}
// console:
// Some Var passed to the handler
// Returned var from handler