Class casting dynamically in swift

后端 未结 5 2014
慢半拍i
慢半拍i 2021-02-19 15:11

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 anyObje         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-19 15:47

    I'm not seeing what the cast at this point is for. You can write:

    let controllersDictionary: [String: String] = [
        "valueOne" : "bar",
        "valueTwo" : "foo"
    ]
    let identifier = controllersDictionary[value]!
    let viewController = storyboard.instantiateViewController(withIdentifier: identifier)
    

    The cast does nothing for you in the code that you have shown. viewController is typed as UIViewController, but it is the correct underlying view controller subclass thanks to polymorphism; whatever the class is in the storyboard, that's the class of this instance.

    The only time you need to cast down is when you have to message an instance with a message belonging only to the subclass, and you have not shown any such need at this point in your code.

提交回复
热议问题