Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send class type after "as!" as an argument

I need to "read" ViewController, which was sent as an argument to a function, as a VC of the specific class. So I need something like that (we get a class also from a function arguments):

let vc = vc_from_func_args as! type_from_func_args

I can pass a class to let's say isMemberOfClass() by doing that:

let klass: AnyClass = MyClass.self
vc.isMemberOfClass(klass)

But I can't do the same thing with "as" expression. It gives me an error:

klass is not a type

How can we pass class (type?) after "as" as a variable?

like image 513
Max Avatar asked Dec 01 '25 18:12

Max


1 Answers

Given your comments, this is exactly what protocols are for. If you want a thing you can call pop on, then make that a requirement for your function. If it's easy to list all the things you need, then just put them in your protocol:

protocol Stackable {
    var parent: UIViewController {get set}
    var child: UIViewController {get set}
}

func push(vc: Stackable) {
    // do the work
}

If you really need this to be a UIViewController that also happens to be Stackable, that's fine, too:

func pop<VC: UIViewController where VC: Stackable>(vc: VC) {
    // do the work
}

Then just mark your view controllers as conforming to Stackable:

class SomeViewController: UIViewController, Stackable {
    var parent: UIViewController
    var child: UIViewController
    ...
 }

If you find yourself doing a lot of as! or AnyClass, you're probably on the wrong track in Swift.

like image 168
Rob Napier Avatar answered Dec 04 '25 09:12

Rob Napier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!