-
Notifications
You must be signed in to change notification settings - Fork 0
/
extensions.swift
85 lines (68 loc) · 2.48 KB
/
extensions.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import Foundation
extension Array where Element: Hashable {
func duplicates() -> Array {
let groups = Dictionary(grouping: self, by: {$0})
let duplicateGroups = groups.filter {$1.count > 1}
let duplicates = Array(duplicateGroups.keys)
return duplicates
}
}
extension NSRegularExpression {
func test(_ string: String) -> Bool {
let range = NSRange(location: 0, length: string.utf16.count)
return firstMatch(in: string, options: [], range: range) != nil
}
}
extension Dictionary where Value: Equatable {
func firstKey(of val: Value) -> Key? {
return self.filter { $1 == val }.map { $0.key }.first
}
}
extension String {
func match(_ regex: NSRegularExpression) -> [[String]] {
let text = self
let matches = regex.matches(in: text, range: NSRange(text.startIndex..., in: text))
return matches.map { match in
return (0..<match.numberOfRanges).map {
let rangeBounds = match.range(at: $0)
guard let range = Range(rangeBounds, in: text) else {
return ""
}
return String(text[range])
}
}
}
func removeCharacters(from forbiddenChars: CharacterSet) -> String {
let passed = self.unicodeScalars.filter { !forbiddenChars.contains($0) }
return String(String.UnicodeScalarView(passed))
}
func removeCharacters(from: String) -> String {
return removeCharacters(from: CharacterSet(charactersIn: from))
}
func except(_ from: String) -> String {
return removeCharacters(from: CharacterSet(charactersIn: from))
}
func paddingLeft(toLength: Int, withPad character: Character) -> String {
let stringLength = self.count
if stringLength < toLength {
return String(repeatElement(character, count: toLength - stringLength)) + self
} else {
return String(self.suffix(toLength))
}
}
subscript(offset: Int) -> String {
String(self[index(startIndex, offsetBy: offset)])
}
}
extension Array {
mutating func shift() -> Element? {
if (self.isEmpty) {
return nil
}
let removed: Element? = self.first
self = self.enumerated().filter { (index, element) -> Bool in
return index != 0
}.map { $0.element }
return removed
}
}