capitalise the first letter of a string in swift

One way to capitalise the first letter of a string in Swift is to use the capitalized property provided by the String class. Here is an example:

main.swift
let str = "hello, world!"
let capitalizedStr = str.capitalized
print(capitalizedStr) // output: "Hello, World!"
112 chars
4 lines

Another way is to use the prefix(1) method to get the first letter, then use the uppercased() method to convert it to uppercase, and finally concatenate it with the rest of the string:

main.swift
let str = "hello, world!"
let firstChar = str.prefix(1).uppercased()
let otherChars = str.dropFirst()
let capitalizedStr = firstChar + otherChars
print(capitalizedStr) // output: "Hello, world!"
195 chars
6 lines

Both of these approaches will result in a string with the first letter capitalized.

gistlibby LogSnag