简体   繁体   中英

How to pass an Int value to an Objective C function from Swift?

I want to pass an integer value from Swift to Objective C function where I can process it .

Objective C function definition is

 (void)getAllDevices:(NSInteger *)limit :(NSInteger *)offset

The Objective C function is part of an SDK called DemoSDK.

I try to pass the value from Swift using this function call

I tried doing doing this

DemoSDK.getAllDevices(10,10)

But the error that comes is

cannot convert a value of type Int to expected argument of type UnsafeMutablePointer

I am very new to Objective C and this is definitely an amateur question. I want to send an int value to objective C function where I can process the int value. How can I do it? Please help.

The parameters aren't asking for integers, they're asking for references to integers. This is achieved with & in Swift.

var limit = Int()
var offset = Int()

DemoSDK.getAllDevices(&limit, &offset)

There are two similar but different methods which can be mistaken.

  • The usual method is

     init(contentsOfURL url: NSURL, encoding enc: UInt) throws 

    The encoding parameter takes an NSStringEncoding value to specify the encoding, for example

     let string = try? String(contentsOfURL:url, encoding:NSUTF8StringEncoding) 

  • The second method retrieves the encoding from the file by passing a pointer as usedEncoding parameter

     init(contentsOfURL url: NSURL, usedEncoding enc: UnsafeMutablePointer<UInt>) throws 

    The documentation says:

    Upon return, if url is read successfully, contains the encoding used to interpret the data.

    That means you have to pass a pointer which will contain the determined encoding of the file.

     var encoding : NSStringEncoding = 0 let string = try? String(contentsOfURL:url, usedEncoding:&encoding) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM