|
16 | 16 |
|
17 | 17 | package struct CamelCaser {
|
18 | 18 | /// Converts a string from upper camel case to lower camel case.
|
19 |
| - package static func toLowerCamelCase(_ s: String) -> String { |
20 |
| - if s.isEmpty { return "" } |
21 |
| - |
22 |
| - let indexOfFirstLowerCase = s.firstIndex(where: { $0 != "_" && $0.lowercased() == String($0) }) |
| 19 | + package static func toLowerCamelCase(_ input: String) -> String { |
| 20 | + guard let indexOfFirstLowercase = input.firstIndex(where: { $0.isLowercase }) else { |
| 21 | + return input.lowercased() |
| 22 | + } |
23 | 23 |
|
24 |
| - if let indexOfFirstLowerCase { |
25 |
| - if indexOfFirstLowerCase == s.startIndex { |
26 |
| - // `s` already begins with a lower case letter. As in: "importCSV". |
27 |
| - return s |
28 |
| - } else if indexOfFirstLowerCase == s.index(after: s.startIndex) { |
29 |
| - // The second character in `s` is lower case. As in: "ImportCSV". |
30 |
| - return s[s.startIndex].lowercased() + s[indexOfFirstLowerCase...] // -> "importCSV" |
31 |
| - } else { |
32 |
| - // The first lower case character is further within `s`. Tentatively, `s` begins with one or |
33 |
| - // more abbreviations. Therefore, the last encountered upper case character could be the |
34 |
| - // beginning of the next word. As in: "FOOBARImportCSV". |
| 24 | + if indexOfFirstLowercase == input.startIndex { |
| 25 | + // `input` already begins with a lower case letter. As in: "importCSV". |
| 26 | + return input |
| 27 | + } else if indexOfFirstLowercase == input.index(after: input.startIndex) { |
| 28 | + // The second character in `input` is lower case. As in: "ImportCSV". |
| 29 | + return input[input.startIndex].lowercased() + input[indexOfFirstLowercase...] // -> "importCSV" |
| 30 | + } else { |
| 31 | + // The first lower case character is further within `input`. Tentatively, `input` begins |
| 32 | + // with one or more abbreviations. Therefore, the last encountered upper case character |
| 33 | + // could be the beginning of the next word. As in: "FOOBARImportCSV". |
35 | 34 |
|
36 |
| - let leadingAbbreviation = s[..<s.index(before: indexOfFirstLowerCase)] |
37 |
| - let followingWords = s[s.index(before: indexOfFirstLowerCase)...] |
| 35 | + let leadingAbbreviation = input[..<input.index(before: indexOfFirstLowercase)] |
| 36 | + let followingWords = input[input.index(before: indexOfFirstLowercase)...] |
38 | 37 |
|
39 |
| - return leadingAbbreviation.lowercased() + followingWords // -> "foobarImportCSV" |
40 |
| - } |
41 |
| - } else { |
42 |
| - // `s` did not contain any lower case letter. |
43 |
| - return s.lowercased() |
| 38 | + return leadingAbbreviation.lowercased() + followingWords // -> "foobarImportCSV" |
44 | 39 | }
|
45 | 40 | }
|
46 | 41 | }
|
0 commit comments