Skip to content

Instantly share code, notes, and snippets.

@shmidt
Created May 16, 2018 16:30
Show Gist options
  • Save shmidt/8ede38604d9e02304c65a5662153ca93 to your computer and use it in GitHub Desktop.
Save shmidt/8ede38604d9e02304c65a5662153ca93 to your computer and use it in GitHub Desktop.
URL+Readlines
//
// String+ReadLines.swift
//
// Created by Dmitry Shmidt on 5/16/18.
//
import Foundation
extension URL{
func readLines() throws -> [String] {
let url = self
let string = try String(contentsOf: url)
let lines = string.splitByNewLines().compactMap{$0.trimmed()}
return lines
}
}
extension String{
func splitByNewLines() -> [String]{
let newlineChars = CharacterSet.newlines
let lines = components(separatedBy: newlineChars).filter{!$0.isEmpty}
return lines
}
func splitBySpace() -> [String]{
let lines = self.split{$0 == " "}.map(String.init)
return lines
}
func splitByCR() -> [String]{
let lines = self.split { $0 == "\r" }.map(String.init)
return lines
}
func splitByNull() -> [String]{
let lines = self.split { $0 == "\0"}.map(String.init)
return lines
}
func splitByWhitespacesAndNewlines() -> [String]{
let newlineChars = CharacterSet.whitespacesAndNewlines
let lines = components(separatedBy: newlineChars).filter{!$0.isEmpty}
return lines
}
func trimmed() -> String {
let trimmedString = self.trimmingCharacters(in: .whitespaces)
return trimmedString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment