Truncate String to Specific Length
If you have entered block of sentence/text and you want to save only specified length out of it text. Add the following extension to Class
If you have entered block of sentence/text and you want to save only specified length out of it text. Add the following extension to Class
extension String { func trunc(_ length: Int) -> String { if self.characters.count > length { return self.substring(to: self.characters.index(self.startIndex, offsetBy: length)) } else { return self } } func trim() -> String{ return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } } Use
Use
var str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry." //str is length 74 print(str) //O/P: Lorem Ipsum is simply dummy text of the printing and typesetting industry. str = str.trunc(40) print(str) //O/P: Lorem Ipsum is simply dummy text of the