get the first 3 characters in a string in swift

To get the first 3 characters of a string in Swift, you can use the following code:

main.swift
let str = "Hello, world!"
let firstThree = String(str.prefix(3))
print(firstThree) // Output: "Hel"
100 chars
4 lines

In the code above, we create a string str and then use the prefix method to get the first three characters of the string. The result of the prefix method is a Substring, so we convert it to a String using the String initializer before printing it. The output of the code is "Hel".

related categories

gistlibby LogSnag