How to pass an error pointer in the Swift language?

后端 未结 2 771
刺人心
刺人心 2021-02-06 20:14

I am attempting to pass an error pointer in swift and am unable to do so. The compiler complains that \"NSError is not convertible to \'NSErrorPointer\'\".

var e         


        
相关标签:
2条回答
  • 2021-02-06 20:56

    This suggestion is up for discussion, but some engineers would prefer to use the golden path syntax:

    var maybeError: NSError?
    if let results = context.executeFetchRequest(request, error: &maybeError) {
        // Work with results
    } else if let error = maybeError {
        // Handle the error
    }
    
    0 讨论(0)
  • 2021-02-06 21:19

    You just pass a reference like so:

    var error: NSError?
    var results = context.executeFetchRequest(request, error: &error)
    
    if error != nil {
        println("Error executing request for entity \(entity)")
    }
    

    Two important points here:

    1. NSError? is an optional (and initialized to nil)
    2. you pass by reference using the & operator (e.g., &error)

    See: Using swift with cocoa and objective-c

    0 讨论(0)
提交回复
热议问题