Ryan Hampton Ryan Hampton - 4 months ago 23
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
String
to
Int16
, as well as the entity and attribute names.

var people = [NSManagedObject]()

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

let managedContext = appDelegate.managedObjectContext

//2
let entity = NSEntityDescription.entityForName("Person",
inManagedObjectContext:managedContext)

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

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

//4
do {
try managedContext.save()
//5
people.append(person)
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}

Answer

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")