Inheritance 单亲继承
我正在Swift中实现单例模式。我需要继承singleton类 我发现了一个提示:Inheritance 单亲继承,inheritance,swift,singleton,Inheritance,Swift,Singleton,我正在Swift中实现单例模式。我需要继承singleton类 我发现了一个提示:[[self-class]alloc]init] 如何用Swift翻译 我想创造一些东西: class var sharedInstance : MyClass //instanceType { struct Static { // something like this static let instance: MyClass = [[[self c
[[self-class]alloc]init]
如何用Swift翻译
我想创造一些东西:
class var sharedInstance : MyClass //instanceType
{
struct Static { // something like this
static let instance: MyClass = [[[self class] alloc] init]
}
return Static.instance
}
谢谢。这是我在swift中的单例继承代码。它似乎在我的项目中起作用
class BaseObject {
required init(){
}
class func shareInstance() ->BaseObject{
let classname = NSStringFromClass(self)
if((dic[classname]) != nil) {
return (dic[classname])!
}
else {
var singletonObject = self()
dic[classname] = singletonObject
return singletonObject
}
}
}
var dic = [String: BaseObject]()
无需使用
[[[self class]alloc]init]
。您可以这样做:
我的班级是斯威夫特
import Foundation
import UIKit
let sharedInstance = MyClass()
class MyClass: NSObject {
func sayHello(){
println("Hello Nurdin!")
}
}
ViewController.swift
/* Code everywhere.. */
sharedInstance.sayHello() //Hello Nurdin! appeared in console.
/* Code everywhere.. */
例如(使用self.init())
Singleton意味着这个类不能有多个实例。 所以构造函数应该是私有的
class YourClassName {
static let sharedInstance: YourClassName = YourClassName()
private override init() {}
}
重复的,但是继承呢?:)不仅基类与上下文相关,还引入了
dic
全局变量。虽然静态变量实际上是全局变量,但让一个类依赖于某个外部变量并没有那么明确的存在原因,这仍然不是一个好主意。
class Base {
}
class A : Base {
static let _a = Base.init()
class var sharedInstance: Base {
return _a
}
}
let a = A.sharedInstance
let b = A.sharedInstance
a === b
class YourClassName {
static let sharedInstance: YourClassName = YourClassName()
private override init() {}
}