无法调用非函数类型的值'((成功:Bool,错误:NSError?)throws - > Void)?)

mos*_*ic6 17 ios swift swift2

我更新到Swift 2和Xcode 7并运行了迁移工具.然后我收到了很多错误.一个我坚持的是这个

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

错误是在完成时(成功:错误,错误和错误)

有什么想法吗?

Rob*_*Rob 27

你是这样调用闭包的:

if completion != nil  {
    completion(success: false, error: error)
}
Run Code Online (Sandbox Code Playgroud)

completion是可选的,因此您可以将其称为:

completion?(success: false, error: error)
Run Code Online (Sandbox Code Playgroud)

请注意?.它也消除了对它的需要if completion != nil ....

-

我注意到你已经定义了闭包,因此它会抛出错误.如果真的如此,那么你需要像do- try- catch块这样的东西:

do {
    try completion?(success:false, error: error)
} catch let completionError {
    print(completionError)
}
Run Code Online (Sandbox Code Playgroud)

要么是这样,要么改变闭包以使它不会抛出错误.这是一个非常好奇的模式.

-

你也有一条线说

var error = NSError.self
Run Code Online (Sandbox Code Playgroud)

我不知道你的意图是什么.你想把什么错误传回封口?

如果您真的想要创建自己的NSError对象,可以执行以下操作:

let error = NSError(domain: "com.domain.app", code: 1, userInfo: [NSLocalizedDescriptionKey : NSLocalizedString("Health Data Not Available", comment: "")])
Run Code Online (Sandbox Code Playgroud)