Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class casting dynamically in swift

Tags:

casting

swift

I am trying to dyanmically cast to a class in Swift. Is this possible? Here is the code I am trying to use:

let stringClass: AnyClass = NSString.self
let anyObject: AnyObject = "foo"
let string = anyObject as! stringClass

The code fails to compile at the cast. Is this possible and if so, why is the right syntax?

Real use case

Here is the real issue. I am attempting to refactor this code:

switch (value) {
    case "valueOne":
        viewController = storyboard.instantiateViewController(withIdentifier: "foo") as! FirstViewController
    case "valueTwo":
        viewController = storyboard.instantiateViewController(withIdentifier: "bar") as! SecondViewController
    default:
        return nil
}

into:

let controllersDictionary: [String: (String, UIViewController.Type)] = [
    "valueOne" : ("bar", FirstViewController.self),
    "valueTwo" : ("foo", SecondViewController.self)
]
let tuple = controllersDictionary[value]!
let identifier = tuple.0
let cast = tuple.1
let viewController = storyboard.instantiateViewController(withIdentifier: identifier) as! cast
like image 403
Alex Curran Avatar asked Aug 05 '16 14:08

Alex Curran


People also ask

What is Upcasting and Downcasting in Swift?

Downcasting is the opposite of upcasting, and it refers to casting an object of a parent class type to an object of its children class. Downcasting is used to reconvert objects of a children class that were upcasted earlier to generalize. Let's say you own two cars and three trucks.

What is Downcasting in Swift?

Downcasting. Downcasting is used to reconvert the object of superclass back to their subclasses. We can think of it as moving down the hierarchy. Like upcasting down casting can only be done within the same hierarchies.

Is vs AS in Swift?

Type casting in Swift is implemented with the is and as operators. is is used to check the type of a value whereas as is used to cast a value to a different type.


1 Answers

I'm not sure exactly what you're trying to achieve, but here's a working version of your example:

func cast<T>(value: Any, to type: T) -> T? {
    return castedValue as? T
}

let inputValue: Any = "this is a test"
let inputType = String.self()
let casted = cast(value: inputValue, to: inputType)

print(casted)
like image 55
Alexander Avatar answered Oct 23 '22 23:10

Alexander