How can I use Swift to call an objective-C method that expects an argument of type (int *)?

后端 未结 1 1565
刺人心
刺人心 2021-01-22 15:39

An existing objective-C method has the following signature:

-(BOOL)barcodeSetScanBeep:(BOOL)enabled volume:(int)volume beepData:(int *)data length:(int)length er         


        
1条回答
  •  广开言路
    2021-01-22 16:11

    int is a C 32-bit integer and mapped to Swift as Int32.

    A int * parameter is mapped to Swift as UnsafeMutablePointer, and you can pass a variable array as "inout parameter" with &.

    So it should roughly look like this:

    var beepData : [ Int32 ] = [ 1200, 100 ]
    var error : NSError?
    if !DTDevices.sharedDevice().barcodeSetScanBeep(true, volume: Int32(100),
                    beepData: &beepData, length: Int32(beepData.count),
                    error: &error) {
        println(error!)
    }
    

    Swift defines also a type alias

    /// The C 'int' type.
    typealias CInt = Int32
    

    so you could replace Int32 by CInt in above code if you want to emphasize that you are working with C integers.

    For more information, see "Interacting with C APIs" in the "Using Swift with Cocoa and Objective-C" documentation.

    0 讨论(0)
提交回复
热议问题