Last active
June 1, 2021 21:34
-
-
Save AmitaiB/bbfcba3a21411ee6d3f972320bcd1ecd to your computer and use it in GitHub Desktop.
CamelCase - CamelCased and llamaCase - llamaCased extensions to String in Swift 3.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
// Swift 3.0 | |
// Helper | |
public extension Character { | |
public var stringValue: String { return String(self) } | |
} | |
extension String { | |
// MARK: - CamelCase | |
// Ironically, function call must be in llamaCase | |
func camelCase() -> String { | |
return self.components(separatedBy: CharacterSet.alphanumerics.inverted) | |
.filter { !$0.isEmpty } | |
.map { $0.capitalized } | |
.joined() | |
} | |
mutating func camelCased() { | |
self = self.camelCase() | |
} | |
// MARK: - LlamaCase | |
func llamaCase() -> String { | |
var result = self.camelCase() | |
if let firstLetter = result.characters.popFirst()?.stringValue { | |
result = firstLetter.lowercased() + result | |
} | |
return result | |
} | |
mutating func llamaCased() { | |
self = self.llamaCase() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Swift apparently dropped the popFirst for strings, so llamaCase no longer works directly. I got it to work as follows: