Swift实现OC中的单例模式

一、MySingle类

import Foundation

class MySingle{
    //定义单例的属性
    var name:String?
    var age:Int?
    var height:Double?
    //定义类方法
    class func shareInstance()->MySingle{
        struct qzSingle{
            static var predicate:dispatch_once_t = 0
            static var instance:MySingle? = nil
        }
        dispatch_once(&qzSingle.predicate,{
                qzSingle.instance = MySingle()
            })
        return qzSingle.instance!
    }
}


二、AppDelegate中调用

//单例的使用
        var single = MySingle.shareInstance()
        single.name = "秦志伟"
        single.age = 24
        single.height = 176.00
        
        println(single)

运行结果:has 3 children

你可能感兴趣的:(Swift(雨燕)教程)