0

Presumably I must be doing something wrong here, but this block of code does not seem to work and I think it should. Can anyone spot what I am doing wrong or might this be a compiler bug?

An exception does get thrown by it does not get caught

enter image description here

According to the docs an exception is raised:

Declaration
SWIFT
func valueForKey(_ key: String) -> AnyObject?
OBJECTIVE-C
- (id _Nullable)valueForKey:(NSString * _Nonnull)key
Parameters
key 
The name of one of the receiver's properties.
Return Value
The value of the property specified by key.

Discussion
If key is not a property defined by the model, the method raises an exception. This method is overridden by NSManagedObject to access the managed object’s generic dictionary storage unless the receiver’s class explicitly provides key-value coding compliant accessor methods for key.
Duncan Groenewald
  • 6,956
  • 4
  • 31
  • 59

1 Answers1

3

Because valueForKey doesn't throw any exceptions.

Look at the signature

func valueForKey(_ key: String) -> AnyObject?

It optionally returns AnyObject, so if the value you're looking for is not there, it will simply return nil.

Just do

if let name = managedObject.valueForKey("displayName") {
  ...   
} else if let name = managedObject.valueForKey("name") {
  ...
}

Bottom line, in swift you can use try only when a function is explicitly marked as throwing an exception. The compiler will check this for you, but you can also look at the function signature to know whether it throws or not.

If valueForKey were throwing an exception, its function signature would look like:

func valueForKey(_ key: String) throws -> AnyObject?
Gabriele Petronella
  • 102,227
  • 20
  • 204
  • 227
  • But it does throw an exception ! NSUnknownKeyException – Duncan Groenewald Oct 16 '15 at 09:50
  • 1
    @DuncanGroenewald The [documentation](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42-ID512) explains that Swift 2's error handling system is *not* meant to catch exceptions. – Eric Aya Oct 16 '15 at 10:33