CamelCaser.swift 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package enum CamelCaser {
  17. /// Converts a string from upper camel case to lower camel case.
  18. package static func toLowerCamelCase(_ input: String) -> String {
  19. guard let indexOfFirstLowercase = input.firstIndex(where: { $0.isLowercase }) else {
  20. return input.lowercased()
  21. }
  22. if indexOfFirstLowercase == input.startIndex {
  23. // `input` already begins with a lower case letter. As in: "importCSV".
  24. return input
  25. } else if indexOfFirstLowercase == input.index(after: input.startIndex) {
  26. // The second character in `input` is lower case. As in: "ImportCSV".
  27. // returns "importCSV"
  28. return input[input.startIndex].lowercased() + input[indexOfFirstLowercase...]
  29. } else {
  30. // The first lower case character is further within `input`. Tentatively, `input` begins
  31. // with one or more abbreviations. Therefore, the last encountered upper case character
  32. // could be the beginning of the next word. As in: "FOOBARImportCSV".
  33. let leadingAbbreviation = input[..<input.index(before: indexOfFirstLowercase)]
  34. let followingWords = input[input.index(before: indexOfFirstLowercase)...]
  35. // returns "foobarImportCSV"
  36. return leadingAbbreviation.lowercased() + followingWords
  37. }
  38. }
  39. }