generics - Swift:在函数失败时向下转换为通用类型

标签 generics swift downcast

我有一个通用函数,它接受任何对象的值和类型为 T 的输入输出参数。我想通过将值向下转换为类型 T 将输入输出参数设置为任何对象的值。

func genericFunction<T>(value:AnyObject, inout object:T) {

    if let castedValue = value as? T {
        object = castedValue
    }
}

当我调用我的函数时,对象的值未设置,因为向下转型失败。

var object:String = "oldValue"
var newValue:String = "newValue"

genericFunction(newValue, &object)
println(object) // prints oldValue

最佳答案

通过将 AnyObject 更改为“Reflectable”解决。还与“任何”合作。 String 实际上并不符合 AnyObject。

func genericFunction<T>(value:Any, inout object:T) {
    if let castedValue = value as? T {
        object = castedValue
    }
}

编辑: Any 是我想要使用的类型,因为 Reflectable 旨在用于反射,而 String 恰好符合它。

关于generics - Swift:在函数失败时向下转换为通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24072482/

相关文章:

c++ - 使用 dynamic_cast 向下转型返回 null

java - 为什么我们真的需要向下转型?

c# - 有没有办法将字符串转换为类型?

scala 泛型函数 `not found: type ?`

generics - 通用密封类的类型安全使用

ios - 将数字字符串转换为不同的区域格式

Go 泛型 : self-referring interface constraint

swift - 为什么 subscribe(subject) 返回 AnyCancellable 但 subscribe(subscriber) Void?

swift Linux。错误 : no such module 'Dispatch'

c++ - 当 Derived 仅添加方法时,将 Base 指针强制转换为 Derived 指针的有效性