KarolisShp KarolisShp -5 years ago 182
Swift Question

Core Data and making double from type AnyObject? Swift

I was writing a code for

. 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
. 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
. I think I should convert anyobject to double to make it work right?

Thanks in advance

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download