我可以安全使用这个较短的单身人士吗?

时间:2016-04-20 13:43:54

标签: ios swift singleton

这是否可以在没有共享实例的情况下制作更短的单身人士? 为什么人们正在创建共享实例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

0 个答案:

没有答案