Skip to content

Instantly share code, notes, and snippets.

@budidino
Forked from vicc/string-truncate.swift
Last active November 22, 2023 17:25
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…"
@salva
Copy link

salva commented May 28, 2019

@namnd, wrong Salva!
You probably meant @SalvatoreAD

@GrootZ7
Copy link

GrootZ7 commented Aug 6, 2019

Thanks a lot!

@Kedar-27
Copy link

Thanks a lot

@dkk
Copy link

dkk commented Apr 6, 2021

Nice Gist, I would just add taking into account the trailing for the length of the string (I also updated the function signature to work with your example):

extension String {
    func truncate(_ length: Int, trailing: String = "…") -> String {        
        (self.count > length) ? self.prefix(max(0, length - trailing.count)) + trailing : self
    }
}

Using your example, let str = "I might be just a little bit too long".truncate(10) would now return a string with 10 characters (I might…), instead of 13 like before (I might be…).

@ppoh71
Copy link

ppoh71 commented Apr 23, 2021

@salva
Something like this

func trunc(length: Int, trailing: String = "…") -> String {
    if (self.count <= length) {
      return self
    }
    var truncated = self.prefix(length)
    while truncated.last != " " {
      truncated = truncated.dropLast()
    }
    return truncated + trailing
  }

Works, just needs a guard in case the string has no " " space

func trunc(length: Int, trailing: String = "…") -> String {
    if (self.count <= length) {
      return self
    }
    var truncated = self.prefix(length)
    while truncated.last != " " {

          guard truncated.count > length else {
            break
          }
      truncated = truncated.dropLast()
    }
    return truncated + trailing
  }
`

@salva
Copy link

salva commented Apr 23, 2021

You keep summoning me, so...

If the main use of trunc is to shorten strings that are too long for presentation purposes, it doesn't make sense to make the replacement when the substitution string is actually longer than the part that is being removed:

A better approach is to let the length argument mean the new length of the string, with trailing included:

var truncated = self.prefix(length - trailing.count)

Then you may like to consider the edge case where the length of trailing is bigger than length.

@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

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