1

Say, I have a C function:

const unsigned char *get_text(int idx);

In my Swift code, I invoke this C function:

let idx: CInt = 6
let txt = get_text(idx)

and I put the txt to a NSMutableDictionary:

var myDict = NSMutableDictionary()
//ERROR: Cannot invoke ‘setValue’ with an argument list of type ’UnsafePointer<UInt8>, forKey: String?)’
myDict.setValue(txt, forKey: “MyText”)

But I get the compiler error above. How can I set the value to my dictionary then?

user842225
  • 5,445
  • 15
  • 69
  • 119
  • 1
    Do you really need it to be a C string in the collection? If not you can use `[NSString stringWithCString:<(const char *)> encoding:<(NSStringEncoding)>];` and store the NSString version of the C string. – Peter Segerblom Sep 09 '15 at 12:00

1 Answers1

4

The C type const unsigned char * is mapped to Swift as UnsafePointer<UInt8>. You can create an (optional) Swift string from that pointer with

let str = String.fromCString(UnsafePointer(txt))
myDict.setValue(str, forKey: "MyText")

This assumes that the C string returned from get_text() is UTF-8 encoded and NUL-terminated.

The UnsafePointer() conversion is necessary because fromCString() takes an UnsafePointer<CChar> argument. If you change the C function to

const char *get_text(int idx);

then it simplifies to

let str = String.fromCString(txt)

Remark: The proper method to set a value in NSMutableDictionary is

setObject(_, forKey: _)

The Key-Value Coding method

setValue(_, forKey: _)

has the same effect in most cases. See for example Where's the difference between setObject:forKey: and setValue:forKey: in NSMutableDictionary? for more information.

You could also consider to use a Swift Dictionary instead.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382