Reputation: 815
I have the following code from a Swift 1.2 tutorial, which I can't manage to convert to Swift 2:
var val: AnyObject? = self.value
var error: NSError?
if !self.myManangedObject.validateValue(&val, forKey: self.key, error: &error) {
var message: String!
if error?.domain == "NSCocoaErrorDomain" {
var userInfo:NSDictionary? = error?.userInfo
var errorKey = userInfo?.valueForKey("NSValidationErrorKey") as String
var reason = error?.localizedFailureReason
message = NSLocalizedString("Validation error on \(errorKey)\rFailure Reason:\(reason)", comment: "Validation error on \(errorKey)\rFailure Reason: \(reason)")
} else {
message = error?.localizedDescription
}
// Create some alerts with the message
}
The self.value
in the first line refers to the value for a CoreData attribute.
I understand I need to change the code to a do { try } catch { }
construct. I am guessing line 3 would look something like this:
try self.myManagedObject.validateValue(&val, forKey: self.key)
However, this doesn't work as Xcode first suggests removing the pointer, and then says
"Cannot convert value of type 'AnyObject?' to expected argument type 'AutoreleasingUnsafeMutablePointer (...)"
Also, I am not sure how to handle the error?.domain
statements. From searching the internet, the examples I found suggest handling the error types in an enumeration, but I don't see how that would apply here.
Btw, would it be possible to use the current version of Xcode to update this code from Swift 1.2 to 2.0?
Upvotes: 1
Views: 1457
Reputation: 57114
The following is the minimal working example for what you are trying to do:
var mgc : NSManagedObjectContext!
var any : AnyObject?
do {
let valid = try mgc.validateValue(&any, forKey: "myKey")
// branch based on the valid
} catch let error as NSError {
// here you go with your error handling
}
Can you take it from here?
Upvotes: 1