0

I am trying to get the last charcter from a given string. I know there is at least 1 character in the string. But when I write the code I get an error.

Here is my code:

func lastCharacter (of string: String) -> Character {
    guard string != "" else { 
        return errorCharacter 
    }

    return string[string.endIndex]
}

Here is the error:

error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

rmaddy
  • 307,833
  • 40
  • 508
  • 550

2 Answers2

4

The endIndex of a thing is not a valid subscript of that thing. It is one beyond the last valid index.

The easiest way to get the last character of a string is to get the suffix(1) of the string or the last of the string.

matt
  • 485,702
  • 82
  • 818
  • 1,064
1

Try

return string.last!

Hope that helps you!

Alexander
  • 54,014
  • 10
  • 87
  • 136
Nick Perkins
  • 180
  • 11