get the first 3 characters and last 5 in a string in swift

One way to get the first 3 characters and last 5 characters in a string in Swift is by using the prefix(_:) and suffix(_:) methods:

main.swift
let myString = "Hello World!"
let firstThree = myString.prefix(3) // "Hel"
let lastFive = myString.suffix(5) // "rld!"
119 chars
4 lines

Another way to achieve the same result is by using the dropLast(_:) and prefix(_:) methods:

main.swift
let myString = "Hello World!"
let firstThree = myString.prefix(3) // "Hel"
let lastFive = myString.dropFirst(myString.count - 5) // "rld!"
139 chars
4 lines

Note that dropFirst(_:) or dropLast(_:) should be used with caution, since they may trigger a runtime error if the string is shorter than the specified number of characters.

related categories

gistlibby LogSnag