Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3/4 dash to camel case (Snake to camelCase)

Tags:

swift

swift3

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?

like image 563
Tomer Avatar asked Dec 18 '25 06:12

Tomer


1 Answers

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)
like image 103
Sulthan Avatar answered Dec 20 '25 20:12

Sulthan