Class casting dynamically in swift

后端 未结 5 2013
慢半拍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 16:04

    While there are/will be ways to make this kind of thing work, the Swifty solution (IMO) is to have your desired classes adhere to a protocol that defines the shared behavior you're trying to use, or simply use a super class they have in common

    This allows the dynamism requried (in most cases at least) while still allowing the compile-time checks that prevent run time errors.

    For your example,

    protocol Stringable {
        func toString() -> String
    }
    
    extension String: Stringable {
        func toString() -> String {
            return self
        }
    }
    
    let thing = "foo"
    let anything: Any = thing
    let test: String? = (anything as? Stringable)?.toString()
    

    Note that this requires "Any" rather than "AnyObject" since you need to cast to a protocol

    Since you mentioned ViewControllers, I thought this might help:

    static func createViewController(storyboard: String, scene: String) -> T? {
        return  UIStoryboard(name: storyboard, bundle: nil).instantiateViewControllerWithIdentifier(scene) as? T
    }
    

提交回复
热议问题