这对我来说有点头脑(对我来说)。基本上我想要从同一个类继承2个不同的单身。在任何一个我想要使用某个本身派生的类。我有Utility
以及AUtil:Utility
和BUtil:Utility
。 Singleton
ASingleton
分别用于AUtility
的{{1}}和B
。我在所有边界都失败了。最后一次尝试是一个工厂模式,只是将Swift 1.2送到Segfault:
protocol Initializable { init() }
class A:Initializable {
var x = "A"
required init() {}
}
class B:Initializable {
var x = "B"
required init() {}
}
class C {
let t:Initializable
init(t:Initializable) {
self.t = t
println(t)
}
func factory() {
println(t.dynamicType())
}
}
如上所述,我还尝试将以下模式设为通用:
private let _SingletonSharedInstance = StaticClass()
class StaticClass {
class var sharedInstance : StaticClass {
return _SingletonSharedInstance
}
}
let s = StaticClass.sharedInstance
(如你所见,这个并不通用。但我所有的尝试都失败了,所以我展示了我的起点。)
无论如何,我似乎在厄运和死亡之间迷失了。
答案 0 :(得分:5)
你的意思是这样吗?
protocol Initializable: class { init() }
private var instances = [String: Initializable]()
func singletonInstance<T: Initializable>(_ ty: T.Type = T.self) -> T {
let name = NSStringFromClass(ty)
if let o = (instances[name] as? T) {
return o
}
let o = ty()
instances[name] = o
return o
}
例如,它的使用方。
class Foo: Initializable { required init() {} }
class Bar: Initializable { required init() {} }
let foo1 = singletonInstance() as Foo // or `singletonInstance(Foo.self)`
let foo2 = singletonInstance() as Foo
assert(foo1 === foo2)
let bar1 = singletonInstance() as Bar
let bar2 = singletonInstance() as Bar
assert(bar1 === bar2)
(我已经测试了上面的代码并让它在Swift 1.2中运行。)
答案 1 :(得分:3)
受findalls实现的启发,我构建了自己的单例生成器,它的功能更强大。
您可以在Swift中创建任何类或结构类型的单例。您唯一需要做的就是为您的类型实现两种不同协议之一,并使用Swift 2.0或更新版本。
public protocol SingletonType { init() }
private var singletonInstances = [String: SingletonType]()
extension SingletonType {
// this will crash Xcode atm. it's a Swift 2.0 beta bug. Bug-ID: 21850697
public static var singleton: Self { return singleton { $0 } }
public static func singleton(setter: (_: Self) -> Self) -> Self {
guard let instance = singletonInstances["\(self)"] as? Self else {
return setInstance(self.init(), withSetter: setter, overridable: true)
}
return setInstance(instance, withSetter: setter, overridable: false)
}
private static func setInstance(var instance: Self, withSetter setter: (_: Self) -> Self, overridable: Bool) -> Self {
instance = restoreInstanceIfNeeded(instance1: instance, instance2: setter(instance), overridable: overridable)
singletonInstances["\(self)"] = instance
return instance
}
private static func restoreInstanceIfNeeded(instance1 i1: Self, instance2 i2: Self, overridable: Bool) -> Self {
// will work if the bug in Swift 2.0 beta is fixed !!! Bug-ID: 21850627
guard i1.dynamicType is AnyClass else { return i2 }
return ((i1 as! AnyObject) !== (i2 as! AnyObject)) && !overridable ? i1 : i2
}
}
这可能看起来有些可怕,但不要害怕这段代码。协议扩展中的公共功能将为您创建两个接入点。 例如,您现在可以编写如下代码:
// extend your type: as an example I will extend 'Int' here
extension Int : SingletonType {} // nothing else to do, because Int already has an 'init()' initializer by default
// let the magic happen
Int.singleton // this will generate a singleton Int with 0 as default value
Int.singleton { (_) -> Int in 100 } // should set your Int singleton to 100
Int.singleton { $0 - 55 } // your singleton should be 45 now
// I need to mention that Xcode will produce the setter like this and trow an error
Int.singleton { (yourCustomInstanceName) -> Self in // replace 'Self' with 'Int' and you should be fine
return yourCustomInstanceName
}
// btw. we just ignored the return value everywhere
print(Int.singleton) // will print 45 here
var singleton2 = Int.singleton { $0 + 5 }
singleton2 += 10
print(Int.singleton) // should print 50, because 'singleton2' is just a copy of an Int value type
class A : SingletonType {
var name = "no name"
required init() {}
}
A.singleton { $0; let i = A(); i.name = "hello world"; return i } // custom init on first singleton call for type A
print(A.singleton.name)
print(A.singleton { $0.name = "A"; return $0 }.name)
print(A.singleton.name)
// should print "hello world" and twice the string "A"
如果您有任何想法如何增强此代码并使其更安全,请告诉我们。我将尽快将此代码推送到GitHub(MIT许可证)上,这样每个人都可以从中受益。
更新:我稍微修改了一下代码,以便您现在可以在第一次调用时使用setter函数传递类的自定义初始化实例。
更新2:我删除了ClassInstance协议并修改了私有恢复功能。 Instance
协议现在称为SingletonType
。 setter函数不再是可选的。 现在Xcode 7 beta 3会崩溃并在您调用getter时提供 illegal instruction: 4
错误。但这是一个已确认的测试版错误。