Trung
Trung

Reputation: 86

Swift: Downcasting to Generic Type in Function Failing

I have a generic function that takes a value of any object and an in-out parameter with type T. I want to set the in-out parameter to the value of the any object by downcasting the value to type T.

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

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

When I call my function, object's value is not set because the downcast fails.

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

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

Upvotes: 2

Views: 1607

Answers (1)

Trung
Trung

Reputation: 86

Solved by changing AnyObject to "Reflectable". Also worked with "Any". String did not actually conform to AnyObject.

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

edit: Any is the type I want to use because Reflectable is meant to be used for Reflection and String happened to conform to it.

Upvotes: 1

Related Questions