我想检查通用变量T
是User
还是Post
的类型,它们都符合协议LiveObject
class LiveManager<T:LiveObject> {
var resources = Dictionary<Int, T>()
init(){
}
func something(){
//How can I check whether T is a User or a Post?
}
}
这是我的全班:
import Foundation
import Firebase
protocol LiveObject {
init(data:JSON)
func startListeningToFirebase(clientName: String) -> Void
func stopListeningToFirebase(clientName: String) -> Void
}
class LiveManager<T:LiveObject> {
let center = NSNotificationCenter.defaultCenter()
let queue = NSOperationQueue.mainQueue()
var resources = Dictionary<Int, T>()
var clients = Dictionary<Int, Set<String>>()
init(){
}
private func addToClientMap(id: Int, clientName: String){
if clients[id] == nil {
clients[id] = Set<String>()
clients[id]!.insert(clientName)
}else{
clients[id]!.insert(clientName)
}
}
func getResource(id: Int, clientName: String) -> T?{
if let resource = resources[id] {
addToClientMap(id, clientName: clientName)
return resource
}else{
return nil
}
}
func createResource(data:JSON, clientName: String, listenToFirebase: Bool) -> T? {
if let id = data["id"].int {
if let resource = resources[id] {
addToClientMap(id, clientName: clientName)
if listenToFirebase { resource.startListeningToFirebase(clientName) }
return resource
}else{
resources[id] = T(data: data)
addToClientMap(id, clientName: clientName)
if listenToFirebase { resources[id]!.startListeningToFirebase(clientName) }
return resources[id]
}
}
return nil
}
func createResource(id: Int, clientName: String, listenToFirebase: Bool, completion:(resource: T?) -> Void) {
}
func releaseResource(id: Int, clientName: String){
print(clientName + " -- release resource")
print(clients)
if clients[id] != nil {
clients[id]!.remove(clientName)
if clients[id]!.count == 0 {
print("Client count is zero - remove this from resources")
resources.removeValueForKey(id)
clients.removeValueForKey(id)
}
}
}
func startListeningToFirebase(id: Int, clientName: String) -> Bool{
if let resource = resources[id] {
resource.startListeningToFirebase(clientName)
return true
}else{
return false
}
}
func stopListeningToFirebase(id: Int, clientName: String) -> Bool{
if let resource = resources[id] {
resource.stopListeningToFirebase(clientName)
return true
}else{
return false
}
}
}
答案 0 :(得分:2)
你可以这样说:
init() {
if T.self == User.self {
print("T is User")
}
else if T.self == Post.self {
print("T is Post")
}
}
然而,虽然你可以做到这一点,但我觉得这样做会破坏使用泛型的目的。
答案 1 :(得分:-1)
检查isKindOfClass和其他相关检查器,具体取决于您要检查的具体内容。