Swift 中的单例 0 个改进

第一种:

class Singleton {
    let name: String
    init(name: String) {
        self.name = name
    }
}

let singleton = Singleton(name: "iOSCaff")

singleton.name

第二种:

class Singleton {
    static let instance = Singleton(name: "iOSCaff")

    let name: String
    private init(name: String) {
        self.name = name
    }
}

Singleton.instance.name

第三种:

class Singleton {
    private static let instanceManager: Singleton = {
        let shared = Singleton(name: "iOSCaff")
        /// do something...
        return shared
    }()

    let name: String
    private init(name: String) {
        self.name = name
    }

    class func instance() -> Singleton {
        return instanceManager
    }
}

Singleton.instance().name
本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!