capitalise the last letter of a string in swift

To capitalize the last letter of a string in Swift, you can use the following code:

main.swift
var myString = "example"
let lastCharacter = myString.last?.uppercased() ?? ""
myString.removeLast()
myString.append(lastCharacter)
print(myString) // "examplE"
161 chars
6 lines

Explanation:

  1. Declare a string variable myString with the value you want to manipulate.
  2. Retrieve the last character of the string using the last property, which returns an optional Character.
  3. Use the nil coalescing operator (??) to provide a default value of an empty string in case the last character is nil.
  4. Use the uppercased() method to capitalize the last character.
  5. Remove the last character from the original string using the removeLast() method.
  6. Append the capitalized last character to the original string using the append() method.
  7. Print the modified string to the console.

This code will output: "examplE"

gistlibby LogSnag