Swift:不能将types'Int16'的值转换为期望的参数types'AnyObject'?

我得到以下错误:

无法将types“Int16”的值转换为期望的参数types“AnyObject?”

在线上

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

当我运行这个应用程序。 该函数的框架从本教程中获取,并从String更改为Int16 ,以及实体和属性名称。

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

正如错误所述, Int16不是Swift中的对象,因此不能在setValue(forKey:) ,它需要一个对象。 尝试将其包装在NSNumber ,如下所示:

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

如果你打算使用Int16,你不能像Int这样的桥接数字types直接把它作为一个对象直接交给Objective-C。 Swift数字不是Objective-C对象,Swift不会帮助你,除了简单的数字,如Int和Double。 对于一个Int16, 必须把它自己封装成一个NSNumber。