Trimming NSAttributedString

Ross Butler
1 min readAug 30, 2018

--

TailorSwift is a GitHub repository created to host useful Swift extensions which constitute notable omissions from the Foundation framework. A recent addition to the repository is a Swift 4 extension which allows a developer to trim a NSAttributedString in the same manner as with NSString by specifying the CharacterSet used to trim the string.

TailorSwift can be incorporated into your project via Cocoapods by adding the following line to your Podfile:

pod "TailorSwift"

Alternatively, if Carthage is your dependency manager of choice, add the following line to your Cartfile:

github "rwbutler/TailorSwift"

Otherwise, the code is available below:

public func trimmingCharacters(in characterSet: CharacterSet) -> NSAttributedString {    let result = self.mutableCopy() as! NSMutableAttributedString    while let range = result.string.rangeOfCharacter(from: characterSet), range.lowerBound == result.string.startIndex {        let length = result.string.distance(from: range.lowerBound, to: range.upperBound)        result.deleteCharacters(in: NSRange(location: 0, length: length))    }    while let range = result.string.rangeOfCharacter(from: characterSet, options: .backwards),        range.upperBound == result.string.endIndex {        let location = result.string.distance(from: result.string.startIndex, to: range.lowerBound)        let length = result.string.distance(from: range.lowerBound, to: range.upperBound)        result.deleteCharacters(in: NSRange(location: location, length: length))    }    return result}

The full code can be viewed on GitHub.

--

--

Ross Butler

Senior Engineering Manager @ Go City. All views are my own.