I am trying to check the meaning of an error code in Swift and get a little confused with new types and conversions.
What I want to do is just take the NSError object passed in the handler closure and check its code type by comparing it with the value stored in the CMError structure. In Objective-C, I will just write
[pedometer queryPedometerDataFromDate:now toDate:now withHandler:^(CMPedometerData *pedometerData, NSError *error) { BOOL isAuthorized = (error.code != CMErrorMotionActivityNotAuthorized); }];
In Swift, when I write what I expect to be equivalent
pedometer.queryPedometerDataFromDate(now, toDate: now) {(data:CMPedometerData!, error:NSError!) in let isAuthorised:Bool = (error.code != CMErrorMotionActivityNotAuthorized) }
I get the error Could not find overload for '! = ', which accepts the provided arguments. This indicates a cast error. And indeed CMErrorMotionActivityNotAuthorized is of type CMError , which is a Swift string. And I cannot convert between this type of CMError and the type of Int , which is of type error.code .
So how can I check my error code?
Note 1
If I try to decompose and explicitly execute:
let errorCode:Int = (CMErrorMotionActivityNotAuthorized as Int) let isAuthorized:Bool = (error.code != errorCode)
I get an absurd error message. Cannot convert expression type "Int" to type "Int".
Note 2
Documentation says CMError is defined as
struct CMError { init(_ value: CUnsignedInt) var value: CUnsignedInt }
in Swift. In Objective-C, it is defined as
typedef enum { CMErrorNULL = 100, CMErrorDeviceRequiresMovement, CMErrorTrueNorthNotAvailable, CMErrorUnknown, CMErrorMotionActivityNotAvailable, CMErrorMotionActivityNotAuthorized, CMErrorMotionActivityNotEntitled, CMErrorInvalidParameter } CMError;