Skip to content

Instantly share code, notes, and snippets.

@pedantix
Last active October 10, 2017 19:04
Show Gist options
  • Save pedantix/9075b399b3a56de1a8c46a7a1af26781 to your computer and use it in GitHub Desktop.
Save pedantix/9075b399b3a56de1a8c46a7a1af26781 to your computer and use it in GitHub Desktop.
truncate by words swift 4
//
// String.swift
// MyModule
//
// Created by Shaun Hubbard on 10/9/17.
// Copyright © 2017 MyCompany, LLC. All rights reserved.
//
import Foundation
extension String {
func truncate(wordCount: Int, trailing: String = "...") -> String {
let words = self.components(separatedBy: CharacterSet.whitespaces)
if words.count > wordCount {
return words[..<wordCount].joined(separator: " ") + trailing
} else {
return self
}
}
}
//
// StringTests.swift
// MyModuleTests
//
// Created by Shaun Hubbard on 10/9/17.
// Copyright © 2017 MyCompany, LLC. All rights reserved.
//
import XCTest
@testable import MyModule
class StringTests: XCTestCase {
func testTruncateWhenToShortByWordCount() {
let testString = "Don't Truncate me"
XCTAssertEqual(testString.truncate(wordCount: 3), testString)
}
func testTruncateWithWordCount() {
let testString = "Do by all means truncate me"
XCTAssertEqual(testString.truncate(wordCount: 3), "Do by all...")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment