KarolisShp KarolisShp - 5 months ago 18
Swift Question

Core Data and making double from type AnyObject? Swift

I was writing a code for

CoreData
. My datamodel includes name and moneyAmount. Here's the part of the code I have troubles with

do {
let request = NSFetchRequest(entityName: "MoneyData")
let results = try context.executeFetchRequest(request)
if results.count > 0 {
for item in results as! [NSManagedObject] {
let name = String(item.valueForKey("name"))
let moneyAmount = item.valueForKey("moneyAmount")
moneyManager.addMoney(name, moneyAmount: moneyAmount)
}
}
} catch {
print("There was an error saving data")
}


Now the problem is that my
moneyManager.addMoney
requires
String
and
Double
. However, with this code, the error that I get is:


Optional Chain has no effect, already produces 'Anyobject?'

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


I don't really understand what it means by
Anyobject
. I think I should convert anyobject to double to make it work right?

Thanks in advance

Jim Jim
Answer

valueForKey() returns an object of type AnyObject because there's no way of knowing at compile-time what type of object it's referencing. You can cast to a specific type using as. For example, moneyAmount as? Double will result in an object of type Double?, either containing the numeric value, or being nil if the object wasn't of type Double.