Jonas Jonas - 1 year ago 110
Swift Question

Convert Swift Function to Objective-C SubstringToIndex

The swift function below hides the key(s) that is pressed on a Bluetooth device display, I'm trying to write this function in Objective-C, however I'm struggling to write characters.count & substringToIndex as shown below in Objective-C, can anyone please help me convert this to Objective-C?

var msg = ""

func captin(leader: CaptinShip!, keyPressed keyCode: UInt) {
print(String(format: "keyPressed: %d (0x%02X)", keyCode, keyCode))

if keyCode == 0 {
msg += "*"
if keyCode == 13 && msg.characters.count > 0 {
msg = msg.substringToIndex(msg.endIndex.advancedBy(-1))

Answer Source

I am assuming that your msg will be a NSString object. If so this should do it:

if (keyCode == 13 && [msg length] > 0) {
    msg = [msg substringToIndex:[msg length] - 2];

But you might consider creating another check on the length of msg, since it will crash if the [msg length] - 2 is out of bounds on the msg length.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download