TIMEX TIMEX - 7 months ago 17
Swift Question

How can I check the type of my generic variable?

I'd like to check whether the generic variable

T
is a type of
User
or
Post
, which both conform to protocol
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?
}
}


This is my full class:

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
}
}
}

Answer

You can say something like this:

init() {
    if T.self == User.self {
        print("T is User")
    }
    else if T.self == Post.self {
        print("T is Post")
    }
}

However, while you can do this, I feel like this kind of defeats the purpose of using generics.

Comments