具有 Swift 3 属性的单例 [英] Singleton with properties in Swift 3
本文介绍了具有 Swift 3 属性的单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Apple 的 将 Swift 与 Cocoa 和 Objective-C 文档一起使用(针对 Swift 3 进行了更新)他们给出了以下单例模式示例:
In Apple's Using Swift with Cocoa and Objective-C document (updated for Swift 3) they give the following example of the Singleton pattern:
class Singleton {
static let sharedInstance: Singleton = {
let instance = Singleton()
// setup code
return instance
}()
}
让我们想象一下,这个单例需要管理一个可变的字符串数组.我将如何/在哪里声明该属性并确保它正确初始化为空的 [String]
数组?
Let's imagine that this singleton needs to manage a variable array of Strings. How/where would I declare that property and ensure it gets initialized properly to an empty [String]
array?
推荐答案
对我来说这是最好的方法,将 init 设为私有.Swift 3 4 5 语法
For me this is the best way, make init private. Swift 3 4 5 syntax
// MARK: - Singleton
final class Singleton {
// Can't init is singleton
private init() { }
// MARK: Shared Instance
static let shared = Singleton()
// MARK: Local Variable
var emptyStringArray = [String]()
}
这篇关于具有 Swift 3 属性的单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文