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

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

This question already has an answer here:

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

回答1:

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


回答2:

If you are going to use an Int16, you cannot hand that off directly to Objective-C as an object the way you can with bridged number types like Int. Swift numbers are not Objective-C objects, and Swift is not going to help you except with simple numbers like Int and Double. For an Int16, you must wrap it up as an NSNumber, yourself.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!