Swift:无法将类型"Int16"的值转换为预期的参数类型"AnyObject?"

Swift:无法将类型

问题描述:

我收到以下错误:

无法将类型"Int16"的值转换为预期的参数类型"AnyObject?"

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

在线

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

当我运行此应用程序时.该功能的框架取自本教程和从String更改为Int16,以及实体和属性名称.

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

如错误所示,Int16在Swift中不是对象,因此不能在需要对象的setValue(forKey:)中使用.尝试将其包装在NSNumber中,如下所示:

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