Ryan Hampton Ryan Hampton - 11 months ago 57
iOS Question

Swift: Cannot convert value of type 'Int16' to expected argument type 'AnyObject?'

I get the following error:

Cannot convert value of type 'Int16' to expected argument type 'AnyObject?'

on the line

person.setValue(Time, forKey: "Time")

when I run this app. The frame of the function was taken from this tutorial and changed from
, as well as the entity and attribute names.

var people = [NSManagedObject]()

func saveName(Time: Int16) {
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate

let managedContext = appDelegate.managedObjectContext

let entity = NSEntityDescription.entityForName("Person",

let person = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)

person.setValue(Time, forKey: "Time")

do {
try managedContext.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")


As the error says, Int16 isn't an object in Swift, and therefore can't be used in setValue(forKey:), which expects an object. Try wrapping it in an NSNumber, like so:

person.setValue(NSNumber(short: Time), forKey: "Time")