Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you cast in swift using a variable for the type

Tags:

casting

swift

I'm looking to try and cast a type based on a variable. The example below fails saying "Use of undeclared type, 'myType'"

protocol Parent {}
protocol Child: Parent {}

struct Foo: Child {}

let foo: Parent = Foo()

let myType = Child.self

if let _ = foo as? myType {
    print("success")
}

Is there any way to cast based on the variable myType?

like image 642
Tal Avatar asked Nov 09 '22 00:11

Tal


1 Answers

Having reflected, casting is not the right question to ask here. Here i'm just checking for conformance. Dynamic casting would be useless as there's no way for the static analyzer to know what to do with it if it's casting based on a variable type.

like image 79
Tal Avatar answered Dec 26 '22 13:12

Tal