Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot call value of non-function type '((success: Bool, error: NSError?) throws -> Void)?)

Tags:

ios

swift

swift2

I updated to Swift 2 and Xcode 7 and ran the migration tool. Then I got a ton of errors. One I'm stuck on is this

func authorizeHealthKit(completion: ((success:Bool, error:NSError?) throws -> Void)?)
{
    // 1. Set the types you want to read from HK Store
    let healthKitTypesToRead = (array:[
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)

        ])

    // 2. Set the types you want to write to HK Store
    let healthKitTypesToWrite = (array:[
        HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
        ])

    // 3. If the store is not available (for instance, iPad) return an error and don't go on.
    if !HKHealthStore.isHealthDataAvailable()
    {
        var error = NSError.self
        if( completion != nil )
        {
            completion(success:false, error:&error)
        }
        return;
    }

    // 4.  Request HealthKit authorization
    healthKitStore.requestAuthorizationToShareTypes(healthKitTypesToWrite as Set<NSObject>, readTypes: healthKitTypesToRead as Set<NSObject>) { (success, error) -> Void in

        if( completion != nil )
        {
            completion(success:success,error:error)
        }
    }
}

The error is on completion(success:false, error&error)

Any thoughts?

like image 308
mosaic6 Avatar asked Sep 24 '15 14:09

mosaic6


1 Answers

You are calling the closure like so:

if completion != nil  {
    completion(success: false, error: error)
}

The completion is optional, so you would call it as:

completion?(success: false, error: error)

Note the ?. It also eliminates the need for the if completion != nil ....

--

I notice that you've defined the closure such that it throws errors. If that's really the case, then you need something like a do-try-catch block:

do {
    try completion?(success:false, error: error)
} catch let completionError {
    print(completionError)
}

Either that, or change the closure so that it doesn't throw errors. That's a pretty curious pattern.

--

You also have a line that says

var error = NSError.self

I don't know what your intent of that is. What error are you trying to pass back to the closure?

If you really wanted to create your own NSError object, you might do something like:

let error = NSError(domain: "com.domain.app", code: 1, userInfo: [NSLocalizedDescriptionKey : NSLocalizedString("Health Data Not Available", comment: "")])
like image 195
Rob Avatar answered Nov 04 '22 12:11

Rob