0

I'd like to return a String back to Swift using this code:

MyFile.h:

+ (char *) myCoolCode;

MyFile.mm:

+(string)myCoolCode {
   string myCoolString = "";
   myCoolString += "123";
   return myCoolString;
}

MyFile.swift:

let superCoolString = MyBridge.myCoolCode()
print(superCoolString)

But obviously it doesn't seems working the right way because it's crashing somewhere deep inside.

See this image

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    Assuming your `string` is a C++ `std::string`, you cannot fake it to `char *` with incompatible header. Also, Swift cannot convert `char *` as Swift `String`. First convert your `myCoolString` into `NSString *` to make Swift convert it to Swift `String`. – OOPer Mar 25 '18 at 11:07
  • Would you be so kind to share some code? `:)` @OOPer –  Mar 25 '18 at 11:09
  • 1
    Why are you defining the return value to be a `char` and in the implementation file a `string`? – Jakub Truhlář Mar 25 '18 at 11:13
  • Because adding "string" instead of "char *" to `MyFile.h` will not work for me so I'm getting errors there @JakubTruhlář. –  Mar 25 '18 at 11:15
  • @OOPer what's the problem with tempi's comment? You indicated that you know the solution but did not present it in a way that's consumable for the OP. So asking for more info seems very reasonable to me. – dr_barto Mar 25 '18 at 13:22
  • @dr_barto, sorry, it's my personal feelings and the comments of tempi in this thread is nothing to do with it. Seems I should delete the comment of mine. One more, please do not hesitate to write an answer if you know what is correct. – OOPer Mar 25 '18 at 13:26

1 Answers1

0

As others have already pointed out in the comments you should fix the return type of your .mm file to char * and not string. You should always keep those two types the same. An example of your function implementation can be:

- (char *)myCoolCode
{
    char str[] = "foobar";
    //You can do whatever you want with str here. Just make sure it's null terminated
    return str;
}

Then in your swift code:

let myCoolString = String(cString: MyBridge.myCoolCode())
print(myCoolString)

Reference on the string constructor is here.

The reason your code was crashing is probably because you were returning an instance of std::string which doesn't really work in Swift. You can use std::string but you have to convert it to char * when returning it. You can do so as is shown here.

Majster
  • 3,611
  • 5
  • 38
  • 60