How to Pass an Error Pointer in the Swift Language

How to pass an error pointer in the Swift language?

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

What is this NSErrorPointer type?

I suggest you read the Pointers section of the Using Swift with Cocoa and Objective-C guide: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8-XID_16

There is a table at the bottom of the Pointers section, which explains how class pointers bridge to Swift pointer types. Based on that, the NSError pointer should be AutoreleasingUnsafePointer<NSError>. Searching trough the headers for NSErrorPointer yields this:

typealias NSErrorPointer = AutoreleasingUnsafePointer<NSError?>

Why the extra ? after NSError? I guess it's because NSError can also be nil.

Hope it helps!

swift programming NSErrorPointer error etc

These types and methods have changed a lot since Swift 1.

  1. The NS prefix is dropped
  2. The methods now throw exceptions instead of taking an error pointer
  3. Use of NSDictionary is discouraged. Instead use a Swift dictionary

This results in the following code:

do {
let object = try JSONSerialization.jsonObject(
with: responseData,
options: .allowFragments)
if let dictionary = object as? [String:Any] {
// do something with the dictionary
}
else {
print("Response data is not a dictionary")
}
}
catch {
print("Error parsing response data: \(error)")
}

Of, if you don't care about the specific parsing error:

let object = try JSONSerialization.jsonObject(
with: responseData,
options: .allowFragments)
if let dictionary = object as? [String:Any] {
// do something with the dictionary
}
else {
print("Response data is not a dictionary")
}

Original Answer

Your NSError has to be defined as an Optional because it can be nil:

var error: NSError?

You also want to account for there being an error in the parsing which will return nil or the parsing returning an array. To do that, we can use an optional casting with the as? operator.

That leaves us with the complete code:

var possibleData = NSJSONSerialization.JSONObjectWithData(
responseData,
options:NSJSONReadingOptions.AllowFragments,
error: &error
) as? NSDictionary;

if let actualError = error {
println("An Error Occurred: \(actualError)")
}
else if let data = possibleData {
// do something with the returned data
}

how to call a function that takes a function pointer argument in Swift?

customCopyDescription needs to be a free function, not a method. When I copied your code into Xcode I got the error message only when customCopyDescription was inside a class, not otherwise.

Once placeholder return values are added and customCopyDescription is placed at file scope, the code compiles without a problem

Pass pointer to var in C function from Swift

Your C function is imported to Swift as

func BufferInit(_ buffer: UnsafeMutablePointer<Buffer>!, _ size: Int32)

and you have to pass the address of a (initialized, nonoptional)
variable of type Buffer as an inout expression.
Structures imported from C have a default constructor in Swift which
initializes all members to zero, so you can write

var buffer = Buffer()
BufferInit(&buffer, 32)

Best practice for Swift methods that can return or error

To add an answer to this question (five years later), there’s a dedicated Result type for this exact scenario. It can return the type you want on success, or type an error on failure.

It does mean re-factoring some code to instead accept a completion handler, and then enumerating over the result in that callback:

class SecurityService {
static func loginWith(email: String, password: String, completionHandler: @escaping (Result<User, SecurityError>) -> Void) {
// Body
}
}

Then in a handler:

securityService.loginWith(email: email, password: password) { result in
switch result {
case .success(let user):
// Do something with user
print("Authenticated as \(user.name)")
case .failure(let error):
// Do something with error
print(error.localizedDescription)
}
}

Swift regards a C const pointer as mutable?

let b is a constant, therefore you cannot pass it as inout argument with &b. But you can use withUnsafePointer(to:) to obtain a (temporary) pointer to its value and pass that to the C function.

let b = MyStruct()
let mystr = withUnsafePointer(to: b) { String(cString: GetBuff($0)) }

Pass FILE* pointer from Swift to C Function

The problem is the wrong usage of absoluteString, so that fopen()
fails and returns nil. The correct way to create a C string from an URL is withUnsafeFileSystemRepresentation:

guard let debugFile = debugDocURL.withUnsafeFileSystemRepresentation( { fopen($0, "w") }) else {
// Could not open file ...
}

Now you can write to the file

xmlDebugDumpNode(debugFile, ...)

and eventually close it:

fclose(debugFile)

An alternative option is to dump the debug output to the (predefined)
“standard error” file:

xmlDebugDumpNode(stderr, ...)

how to pass a swift Array as UnsafePointer T argument in a function

Change your colors type to be explicitly [CGFloat]:

var colors : [CGFloat] = [0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0]

No need to deal with & or anything. But you have to actually pass in an array of CGFloat.

And don't pass in NULL but nil:

let gradient = CGGradientCreateWithColorComponents(baseSpace, colors, nil, 2)


Related Topics



Leave a reply



Submit