Last active
October 10, 2017 19:04
-
-
Save pedantix/9075b399b3a56de1a8c46a7a1af26781 to your computer and use it in GitHub Desktop.
truncate by words swift 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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