Skip to content

Instantly share code, notes, and snippets.

@budidino
Forked from vicc/string-truncate.swift
Last active April 3, 2024 20:11
Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save budidino/8585eecd55fd4284afaaef762450f98e to your computer and use it in GitHub Desktop.
Save budidino/8585eecd55fd4284afaaef762450f98e to your computer and use it in GitHub Desktop.
String truncate extension for Swift 4
extension String {
/*
Truncates the string to the specified length number of characters and appends an optional trailing string if longer.
- Parameter length: Desired maximum lengths of a string
- Parameter trailing: A 'String' that will be appended after the truncation.
- Returns: 'String' object.
*/
func trunc(length: Int, trailing: String = "") -> String {
return (self.count > length) ? self.prefix(length) + trailing : self
}
}
// Swift 4.0 Example
let str = "I might be just a little bit too long".truncate(10) // "I might be…"
@ChediB
Copy link

ChediB commented Oct 3, 2022

A safe version :

extension String {
    func trunc(length: Int, trailing: String = "…") -> String {
        let maxLength = length - trailing.count
        guard maxLength > 0, !self.isEmpty, self.count > length else {
            return self
        }
        return self.prefix(maxLength) + trailing
    }
}

@aviwad
Copy link

aviwad commented Aug 27, 2023

Thanks. Have used in my project SpotifyLyricsInMenubar

@NishayKumar
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment