Forced deployment against

Facebook recently updated Parse to support Swift. One example of the code that he gives is:

var gameScore = PFObject(className: "GameScore") gameScore.setObject(1337, forKey: "score") gameScore.setObject("Sean Plott", forKey: "playerName") gameScore.saveInBackgroundWithBlock { (success: Bool!, error: NSError!) -> Void in if success { NSLog("Object created with id: \(gameScore.objectId)") } else { NSLog("%@", error) } } 

I am interested in this part: "(success: Bool !, error: NSError!)", In particular, the exclamation point item. My understanding of options was something like this:

NSError: This is an NSError and cannot be nil. NSError ?: this may include NSError or it may be zero, but you need to deploy it first. NSError !: this is a deployed force of NSError ?, and therefore cannot be nil.

On Facebook, an example says success is Bool! and the error is NSError! - that is, they are both guaranteed. Why aren't they just written as Bool and NSError if they opened Facebook before posting them? In addition, how can one establish both success and error? The traditional use of NSError will say that it is set to zero when there is no problem.

+6
source share
2 answers

This is probably due to compatibility with the Objective-C API. Since any object can be nil in Objective-C, these two values ​​must be optional in Swift.

In any case, since they apparently guarantee that these objects will never be nil - they can allow them to implicitly expand them, allowing those using this API to save multiple unpacks, which is nice.

Regarding your statement

The traditional use of NSError means that it is set to zero when there is no problem.

This is simply wrong, even in Objective-C.

Cocoa's BOOL / NSError pattern indicates that you need to check the success value to see if an error has occurred, and - if this is the case - then NSError will contain information about it.

Checking NSError for nil is a common misuse of this pattern, and this can lead to logic errors in your code, as some Apple APIs return a non nil error even if successful.

+4
source

On Facebook, an example says success is Bool! and the error is NSError! - that is, they are both guaranteed.

yes they are. remember that a zero error code ( 0 ) usually indicates successful transactions, it is much more logical than sending nil .

Also, how to establish both success and error? The traditional use of NSError will say that it is set to zero when there is no problem.

which tells you (implicitly) if any error occurs, error will always be provided for your block as a valid error message.

0
source

Source: https://habr.com/ru/post/970801/


All Articles