Truncate a String in Swift 2.0

I've been working on a project developing an iOS app in Swift and found the need to trim a string down to a specific number of characters. Since most of my coding experience was with the web, I started searching for the easy to use equivalent of Javascript's .substring() function. Unfortunately I wasn't able to find one that was so cut and dry. I did however take what I was able to find and extend the String class to add my own function to it.

In order to create an extension of the String class I opened a new file and named it String-Extension.swift. This may or may not be standard procedure, but it's the way I work. Once I had the file open, I started with:

import Foundation

and then extended the String class:

extension String { }

Inside the brackets I create a function called trunc that accepts 1 required argument and 1 optional argument with a default of "..." that returns a String:

func trunc(length: Int, trailing: String? = "...") -> String { }

From there I had to check to make sure the string was actually longer than what I was trying to trim it down to and do nothing if it isn't:

if self.characters.count > length {
} else {
    return self
}

In the first part of that if statement we need to return the trimmed string which is done by running substringToIndex on the string, starting at the first character and extending to the length provided and then adding the trailing characters (either the default or provided value):

return self.substringToIndex(self.startIndex.advancedBy(length)) + (trailing ?? "")

Putting it all together you get:

import Foundation

extension String {
    func trunc(length: Int, trailing: String? = "...") -> String {
        if self.characters.count > length {
            return self.substringToIndex(self.startIndex.advancedBy(length)) + (trailing ?? "")
        } else {
            return self
        }
     }
}

Let's create a string to truncate:

let str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis non sem in nulla malesuada iaculis. Aenean non sem finibus, faucibus ex eget, accumsan nulla. In hac habitasse platea dictumst. Sed metus."

...and assign it to a label's text using our new function:

label.text = str.trunc(100)

That label will now display:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis non sem in nulla malesuada iaculis. Ae...

If we change the trailing value to something like "... :)" we would get:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis non sem in nulla malesuada iaculis. Ae... :)

And that's it! If you have any changes or updates (especially as Swift continues to evolve) just leave a comment below.

comments powered by Disqus
© 2017. All rights reserved.
© 2017. All rights reserved.