Skip to content

Instantly share code, notes, and snippets.

@AmitaiB
Last active June 1, 2021 21:34
Show Gist options
  • Save AmitaiB/bbfcba3a21411ee6d3f972320bcd1ecd to your computer and use it in GitHub Desktop.
Save AmitaiB/bbfcba3a21411ee6d3f972320bcd1ecd to your computer and use it in GitHub Desktop.
CamelCase - CamelCased and llamaCase - llamaCased extensions to String in Swift 3.0
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()
}
}
@RDStewart
Copy link

Swift apparently dropped the popFirst for strings, so llamaCase no longer works directly. I got it to work as follows:

func llamaCase() -> String {
	var result = self.camelCase()
	if result != "" {
		let firstLetter = result.removeFirst().stringValue
		result = firstLetter.lowercased() + result
	}
	return result
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment