Skip to content

Instantly share code, notes, and snippets.

@erica erica/camel.swift

Last active Feb 2, 2018
Embed
What would you like to do?
public extension String {
public func rangeFromNSRange(aRange: NSRange) -> Range<String.Index> {
let s = advance(self.startIndex, aRange.location)
let e = advance(self.startIndex, aRange.location + aRange.length)
return s..<e
}
public var ns : NSString {return self as NSString}
public subscript (aRange: NSRange) -> String? {
get {return self.substringWithRange(self.rangeFromNSRange(aRange))}
}
public var cdr: String {return isEmpty ? "" : String(characters.dropFirst())}
public func toSnake() throws -> String {
var s = self
let regex = try NSRegularExpression(pattern: "[:upper:]+", options: [])
let matches = regex.matchesInString(s, options:[], range:NSMakeRange(0, s.ns.length)).reverse()
for match in matches {
let matchRange = s.rangeFromNSRange(match.range)
let lc = s[match.range]!.lowercaseString
s.replaceRange(matchRange, with: "_" + lc)
}
if s.hasPrefix("_") {s = String(s.characters.dropFirst())}
return s
}
public func toScreamingSnake() throws -> String {
return try self.toSnake().uppercaseString
}
public func toCamel() throws -> String {
var s = self
let regex = try NSRegularExpression(pattern: "_.", options: [])
let matches = regex.matchesInString(s, options:[], range:NSMakeRange(0, s.ns.length)).reverse()
for match in matches {
let matchRange = s.rangeFromNSRange(match.range)
let uc = s[match.range]!.uppercaseString.cdr
s.replaceRange(matchRange, with: uc)
}
if s.hasPrefix("_") {s = s.cdr}
return s
}
}
let s = "helloWorld"
try s.toSnake()
try s.toSnake().toCamel()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.