I am trying to perform a simple dash to camel case so: "this-is-my-id" will become "thisIsMyId" in swift 3 (or 4).
No matter what I do I can't find an elegant enough way to do it..: The following doesn't work:
str.split(separator: "-").enumerated().map { (index, element) in
return index > 0 ? element.capitalized : element
}.reduce("", +)
It cries about all bunch of stuff. I am sure there is a simple enough way... Anyone?
Your code is almost correct. The following is the most readable implementation I have found:
let str: String = "this-is-my-id"
let result = str
.split(separator: "-") // split to components
.map { String($0) } // convert subsequences to String
.enumerated() // get indices
.map { $0.offset > 0 ? $0.element.capitalized : $0.element.lowercased() } // added lowercasing
.joined() // join to one string
print(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With