2017-01-11 1 views
0

J'ai un programme sur HID. Mais il est écrit en Objective-C. C'est un projet et mes amis ne savent que vite. J'ai donc pensé à le convertir en rapide et je n'arrive pas à comprendre comment écrire cette fonction.Comment écrire la fonction HID Handle_DeviceMatchingCallback dans swift?

code Obj-c:

/* Creating The HID Manager */ 
IOHIDManagerRef manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); 
/* Dictionary Matching - All the devices */ 
IOHIDManagerSetDeviceMatching(manager,NULL); 
/* Connected and Disconnected Call Backs */ 
IOHIDManagerRegisterDeviceMatchingCallback(manager, &Handle_DeviceMatchingCallback , NULL); 
IOHIDManagerRegisterDeviceRemovalCallback(manager, &Handle_DeviceRemovalCallback,NULL); 

Et l'appel sur les fonctions sont les suivantes:

static void Handle_DeviceMatchingCallback(void *inContext, 
              IOReturn inResult, 
              void *inSender, 
              IOHIDDeviceRef inIOHIDDeviceRef) 
{ 
    printf("Connected\n"); 



} 


static void Handle_DeviceRemovalCallback(void *inContext, 
             IOReturn inResult, 
             void *inSender, 
             IOHIDDeviceRef inIOHIDDeviceRef) 
{ 
    printf("Disconnected\n"); 
} 

En rapide,

j'ai écrit Handle_DeviceMatchingCallback() comme

func Handle_DeviceMatchingCallback(inContext: UnsafeMutableRawPointer!, inResult: IOReturn, inSender: UnsafeMutableRawPointer!, inIOHIDDeviceRef: IOHIDDevice) 
{ 
    print("Connected") 
} 

Mais je ne peux pas passer la fonction à IOHIDManagerRegisterDeviceMatchingCallback().

Comment faire?

Répondre

2

Une façon de traiter votre cas fait les callbacks que les fermetures:

let Handle_DeviceMatchingCallback: IOHIDDeviceCallback = {context, result, sender, device in 
    print("Connected") 
} 
let Handle_DeviceRemovalCallback: IOHIDDeviceCallback = {context, result, sender, device in 
    print("Disconnected") 
} 

Ou bien, vous devez déclarer les fonctions de rappel avec exactement la même signature que défini dans IOHIDDeviceCallback.

typealias IOHIDDeviceCallback = (UnsafeMutableRawPointer?, IOReturn, 
    UnsafeMutableRawPointer?, IOHIDDevice) -> Void 

(Taken de l'aide rapide de Xcode.)

func Handle_DeviceMatchingCallback(_ context: UnsafeMutableRawPointer?, _ result: IOReturn, _ sender: UnsafeMutableRawPointer?, _ device: IOHIDDevice) { 
    print("Connected") 
} 
func Handle_DeviceRemovalCallback(_ context: UnsafeMutableRawPointer?, _ result: IOReturn, _ sender: UnsafeMutableRawPointer?, _ device: IOHIDDevice) { 
    print("Disconnected") 
}