Feru
Feru

Reputation: 1221

Passing class type in a variable

In swift 2.0 is there a way to pass the type of the class in a variable so that I can later use it for checking if a object type 'is' that class type. Better explained thru following example :

class Base {..}
class Derived : Base {..}
var obj: Base = Derived()
if obj is Derived {
   print("obj is Derived type")
}

This is fine. But I want to be ability to store the class type 'Derived' in a variable something like this :

let classType = Derived  // Of course this will give compile error

And use it later to check the type of an object :

if obj is classType {..}

The closest I came to dealing with saving the Class type is:

let classType = Derived.self

This says the classType is of type 'Derived.Type', but you can't really use that for checking the object type as below :

if obj is classType {..blah.. } // Compile error.'Use of undeclared type 'classType'

I hope you are getting my point. I'm trying to store the class type in a variable and later use that to check if the object belongs to that type. Is there a way to do it. I looked at similar forums on stack overflow but nothing which came close to answering this.

Upvotes: 1

Views: 1781

Answers (3)

ElFitz
ElFitz

Reputation: 988

@matt's answer works with Swift 2.0. In swift 3 you can simply do the following:

    class Base {}
    class Derived : Base {}

    var obj: Base = Derived()
    let aClassType = Derived.self

    if type(of: obj) == aClassType {
        print("hey !")
    }

Unless === is better. I don't get the difference.

Upvotes: 1

Michał Majewski
Michał Majewski

Reputation: 1

I may have a solution which doesn't need to create an instance of saved type.

The idea is to create a generic struct conforming to protocol P with a typealias inside. Then we can create instances of that struct and pass them to a function, which accepts an argument conforming to P and has access to a type via typealias in protocol.

Lets create something like this:

protocol TypeContainerP {
    typealias type
}

struct TypeContainer<T>: TypeContainerP {
    typealias type = T
}

Now we can create instance of TypeContainer parameterized with some types:

class A {}
class B {}
let containerA = TypeContainer<A>()
let containerB = TypeContainer<B>()

and create function, which has TypeContainerP as an argument and gives us access to type via protocol:

func check<T, E: TypeContainerP>(any: T, _: E) {
    print(any is E.type)
}

and we have:

check(A(), containerA) // true
check(A(), containerB) // false
check(B(), containerA) // false
check(B(), containerB) // true

Upvotes: 0

matt
matt

Reputation: 534885

Like this:

    class Base {}
    class Derived : Base {}
    var obj: Base = Derived()
    if obj.dynamicType === Derived.self {
        print("obj is Derived type")
    }

Upvotes: 2

Related Questions