我编写了一个涉及单身人士的应用,我试图从我的应用中的其他文件中访问单例文件。这是我的代码:
Singleton.swift
socketId
OutofQuestionsVC.swift
export function sendTodosByUserId(io, userId) {
//How to auth? By linking a client socketId to a user in a lookup table?
connect()
.then(conn => {
r
.table('todos')
.filter(todos => todos("userId").eq(userId))
.changes().run(conn, (err, cursor) => {
cursor.each((err, change) => {
//Do I emit a unique message? namespace? How do I handle 2 clients using the same userId?
io.emit('TODO_CHANGE', change);
});
});
});
}
答案 0 :(得分:0)
github上的Design-Patterns-In-Swift项目有一个例子
https://github.com/ochococo/Design-Patterns-In-Swift/blob/master/source/creational/singleton.swift
示例:
class DeathStarSuperlaser {
static let sharedInstance = DeathStarSuperlaser()
private init() {
// Private initialization to ensure just one instance is created.
}
}
用法:
let laser = DeathStarSuperlaser.sharedInstance
答案 1 :(得分:0)
要设置课程,您可以这样做:
class Singelton {
class var sharedSingelton : Singelton {
struct Static {
static let instance : Singelton = Singelton()
}
return Static.instance
}
}
并且用于初始化(将自动完成,如果您第一次访问单例。第二次等实例将被返回)您可以这样做:
let singelton = Singelton.sharedSingelton
仅限
Singelton.sharedSingelton