Yury Loginov
Yury Loginov

Reputation: 475

Swift 3. Cast Any to class which conforms specific protocol

I have a random protocol as example

protocol testP {
    init(param1: String)
}

And I have a class, which take Any as parameter as example:

class testC {
    var aClass: Any
}

How can I check if aClass conforms to protocol testP and if it does, create a new object using protocol initializer, as example:

let newObject = aClass(param1: "Hello World!")

Please, help

Upvotes: 3

Views: 634

Answers (1)

OOPer
OOPer

Reputation: 47886

You can test it as other type checking with if-let:

protocol TestP {
    init(param1: String)
}

class TestC {
    var aClass: Any

    init(_ aClass: Any) {
        self.aClass = aClass
    }
}

class MyClassA: TestP {
    required init(param1: String) {
        //
    }
}

class MyClassB {

}

let containerA = TestC(MyClassA.self)

let containerB = TestC(MyClassB.self)

if let testPType = containerA.aClass as? TestP.Type {
    var a = testPType.init(param1: "abc")
    print(a) //->MyClassA
}

if let testPType = containerB.aClass as? TestP.Type {
    print("This print statement is not executed")
}

By the way, if you assign only class types to aClass, consider using AnyClass or Any.Type.

Upvotes: 1

Related Questions