Ryan Hampton Ryan Hampton - 1 year ago 59
iOS Question

Swift: Could not cast value of type Swift.Int16 to Swift.AnyObject

Getting the error message 'Could not cast value of type Swift.Int16 to Swift.AnyObject' when I run the line of code below. The error occurs on the line:

'newWorkout.setValue(totalTimeConverted as! AnyObject, forKey: "workoutTime")'

Workout is the name of my entity. It has two attributes;

  • workoutDate of type NSDate

  • workoutTime of type Int16.

    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext

    let newWorkout = NSEntityDescription.insertNewObjectForEntityForName("Workout", inManagedObjectContext: context) as! Workout

    let totalTimeConverted = Int16(totalTime)

    // Add parameters
    newWorkout.setValue(totalTimeConverted as! AnyObject, forKey: "workoutTime")
    newWorkout.setValue(NSDate(), forKey: "workoutDate")

    do {
    try context.save()
    } catch {
    print("Error saving data")

    do {
    let request = NSFetchRequest(entityName: "Workout")
    let results = try context.executeFetchRequest(request)
    if results.count > 0 {

    for item in results as! [NSManagedObject]{

    let time = item.valueForKey("workoutTime")
    let workoutDate = item.valueForKey("workoutDate")
    print(time!, workoutDate!)

    } catch{
    print("Error loading data")

Answer Source

You cannot cast Int16 to AnyObject. It is value type and not class.

You can use NSInteger to do proper typecasting

newWorkout.setValue(NSInteger(totalTimeConverted), forKey: "workoutTime")