Class casting dynamically in swift

后端 未结 5 2020
慢半拍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:39

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

    func cast(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)
    

提交回复
热议问题