-
Notifications
You must be signed in to change notification settings - Fork 104
/
String+Extensions.swift
52 lines (43 loc) · 1.42 KB
/
String+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
// Copyright (c) 2018-2020 XMLCoder contributors
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
//
// Created by Vincent Esche on 12/18/18.
//
import Foundation
extension StringProtocol where Self.Index == String.Index {
func escape(_ characterSet: [(character: String, escapedCharacter: String)]) -> String {
var string = String(self)
for set in characterSet {
string = string.replacingOccurrences(of: set.character, with: set.escapedCharacter, options: .literal)
}
return string
}
}
extension StringProtocol {
func capitalizingFirstLetter() -> Self {
guard !isEmpty else {
return self
}
return Self(prefix(1).uppercased() + dropFirst())!
}
mutating func capitalizeFirstLetter() {
self = capitalizingFirstLetter()
}
func lowercasingFirstLetter() -> Self {
// avoid lowercasing single letters (I), or capitalized multiples (AThing ! to aThing, leave as AThing)
guard count > 1, !(String(prefix(2)) == prefix(2).lowercased()) else {
return self
}
return Self(prefix(1).lowercased() + dropFirst())!
}
mutating func lowercaseFirstLetter() {
self = lowercasingFirstLetter()
}
}
extension String {
func isAllWhitespace() -> Bool {
return self.trimmingCharacters(in: .whitespacesAndNewlines) == ""
}
}