Search code examples
swiftswift3

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


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?


Solution

  • A combination of all these answers will lead to the following, shortest way (I think - only 2 interations):

    let str: String = "this-is-my-id"
    
    let result = str.split(separator: "-").reduce("") {(acc, name) in
        "\(acc)\(acc.count > 0 ? String(name.capitalized) : String(name))"
    }
    

    Thanks all!