DomainDig/StringConveniences.swift
32 lines · 1093 bytes
1import Foundation
2
3/// Two different questions, with two names.
4///
5/// Seven files used to declare a private `nilIfEmpty`, and one of them —
6/// `DomainInsightEngine` — trimmed whitespace first while the rest did not, so
7/// the same name meant two things and nothing could be shared (A14). Naming the
8/// trimming one `nilIfBlank` separates them, which is what lets there be one
9/// copy of each.
10extension String {
11 /// `nil` when there is nothing at all, keeping a string of spaces.
12 ///
13 /// For values already normalised upstream, where whitespace would be
14 /// content rather than noise.
15 var nilIfEmpty: String? {
16 isEmpty ? nil : self
17 }
18
19 /// `nil` when there is nothing but whitespace, and trimmed otherwise.
20 ///
21 /// For values straight from a text field or an imported row.
22 var nilIfBlank: String? {
23 let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
24 return trimmed.isEmpty ? nil : trimmed
25 }
26}
27
28extension Array where Element == String {
29 var nilIfEmpty: [String]? {
30 isEmpty ? nil : self
31 }
32}