2

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
Trung
  • 86
  • 5

1 Answers1

1

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.

Trung
  • 86
  • 5
  • 1
    This works only if the value is bridgeable to Any. But what if there are only AnyObjects like with ObjC objects (values from NSDictionaries for example)? – Florian Friedrich Jun 09 '14 at 13:11