In Swift
you can write,
func right(value: String, length: Int) -> String {
if value.count <= length {
return value
} else {
let index = value.index(value.startIndex, offsetBy: value.count-length)
return String(value[..<index])
}
}
There is no need to check for empty string
. It will be covered in the else condition
itself.
Example:
right(value: "abcdefgh", length: 3) //abcde