Skip to content

Instantly share code, notes, and snippets.

@nedimf
Last active November 21, 2020 20:22
Truncate string and add "..." in the end - SWIFT
//Extension on String
extension String {
func truncating(max:Int) -> String{
let text = self
print("passed text \(text)")
if text.count >= max {
let truncatedIndex = text.index((text.startIndex), offsetBy: max)
let truncated = text.substring(to: truncatedIndex)
let t = truncated.appending("...")
print("truncated string", t.description)
return t.description
}else{
return self
}
}
}
//Call
label.text = textOfLabel.truncating(max: 24) //max 24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment