在Swift 3中具有属性的Singleton [英] Singleton with properties in Swift 3
本文介绍了在Swift 3中具有属性的Singleton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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数组.我将如何/在何处声明该属性并确保将其正确初始化为空的[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中具有属性的Singleton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文