Swift:无法将类型"Int16"的值转换为预期的参数类型"AnyObject?" [英] Swift: Cannot convert value of type 'Int16' to expected argument type 'AnyObject?'
本文介绍了Swift:无法将类型"Int16"的值转换为预期的参数类型"AnyObject?"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到以下错误:
无法将类型"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")
这篇关于Swift:无法将类型"Int16"的值转换为预期的参数类型"AnyObject?"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文