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
  • 314,917
  • 42
  • 532
  • 579

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
  • 515,959
  • 87
  • 875
  • 1,141
1

Try

return string.last!

Hope that helps you!

Alexander
  • 59,041
  • 12
  • 98
  • 151
Nick Perkins
  • 206
  • 1
  • 12