Swift 3/4 dash to camel case (Snake to camelCase)
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!
Codable decoding values in JSON converting snake case to camel
Wound up adding a custom decoding initializer on Foo
:
public init(from decoder: Decoder) throws {
let rawValue = try decoder.singleValueContainer().decode(String.self)
if let foo = Self.init(rawValue: rawValue.snakeToCamelCase) {
self = foo
} else {
throw CodingError.unknownValue
}
}
snakeToCamelCase
is a simple extension method on String
I added locally. Plus need to add the enum CodingError: Error
to Foo
if you want some error handling.
This isn't ideal but at least it's not too complicated. I would rather rely on built-in case conversion methods but I don't see a way to do that here.
What is the difference between combining array by using reduce or joined?
There are two reasons why joined
is a better choice than reduce
:
Readability
If you want to join multiple strings into one string, why would you use
reduce
, with manual concatenation? If there is a specific function for the task you want to do, use it. When reading the code, it's easier to understandjoined
thanreduce
.Performance
joined
forString
can be implemented better thanreduce
. It does not have to be but it can.reduce
operates on one element at a time, without knowledge about the other elements, with many temporary variables passed around.joined
has the knowledge of the entire sequence and it knows that the operation is always the same, therefore it can optimize. It can even use the internal structure ofString
. See String.joined implementation.
In summary, always use the more specific implementation.
Note that the performance reason above is the less important one.
When creating a VSCode snippet, how can I transform a variable to title-case (like TitleCase)?
Try this:
"My Snippet": {
"scope": "typescript",
"prefix": "snippet",
"body": [
"${1}() {",
// "\treturn this.get(${TM_FILENAME_BASE/([a-z]*)-*([a-z]*)/${1:/capitalize}${2:/capitalize}/g}.FIELD.${3});",
"\treturn this.get(${TM_FILENAME_BASE/(.*)/${1:/pascalcase}/g}.FIELD.${3});",
"}",
"",
"$0"
],
"description": "Creates a function wrapper for a model's attribute."
}
EDIT : In October, 2018 the \pascalcase
transform was added to vscode - see
commit, but not yet added to the documentation (as of the date of this edit). I have added the much simpler transform above which accomplishes the PascalCase transform.
Demo added, uses the clipboard after the first filename case (test-bed-snippets.xxx
) just to make the various possibilities easy to demonstrate.
See also snippet transform to CamelCase
Convert camelCaseText to Title Case Text
const text = 'helloThereMister';
const result = text.replace(/([A-Z])/g, " $1");
const finalResult = result.charAt(0).toUpperCase() + result.slice(1);
console.log(finalResult);
Separating CamelCase string into space-separated words in Swift
As far as I tested on my old MacBook, your code seems to be efficient enough for short strings:
import Foundation
extension String {
var camelCaps: String {
var newString: String = ""
let upperCase = CharacterSet.uppercaseLetters
for scalar in self.unicodeScalars {
if upperCase.contains(scalar) {
newString.append(" ")
}
let character = Character(scalar)
newString.append(character)
}
return newString
}
var camelCaps2: String {
var newString: String = ""
let upperCase = CharacterSet.uppercaseLetters
var range = self.startIndex..<self.endIndex
while let foundRange = self.rangeOfCharacter(from: upperCase,range: range) {
newString += self.substring(with: range.lowerBound..<foundRange.lowerBound)
newString += " "
newString += self.substring(with: foundRange)
range = foundRange.upperBound..<self.endIndex
}
newString += self.substring(with: range)
return newString
}
var camelCaps3: String {
struct My {
static let regex = try! NSRegularExpression(pattern: "[A-Z]")
}
return My.regex.stringByReplacingMatches(in: self, range: NSRange(0..<self.utf16.count), withTemplate: " $0")
}
}
let aCamelCaps = "aCamelCaps"
assert(aCamelCaps.camelCaps == aCamelCaps.camelCaps2)
assert(aCamelCaps.camelCaps == aCamelCaps.camelCaps3)
let t0 = Date().timeIntervalSinceReferenceDate
for _ in 0..<1_000_000 {
let aCamelCaps = "aCamelCaps"
let camelCapped = aCamelCaps.camelCaps
}
let t1 = Date().timeIntervalSinceReferenceDate
print(t1-t0) //->4.78703999519348
for _ in 0..<1_000_000 {
let aCamelCaps = "aCamelCaps"
let camelCapped = aCamelCaps.camelCaps2
}
let t2 = Date().timeIntervalSinceReferenceDate
print(t2-t1) //->10.5831440091133
for _ in 0..<1_000_000 {
let aCamelCaps = "aCamelCaps"
let camelCapped = aCamelCaps.camelCaps3
}
let t3 = Date().timeIntervalSinceReferenceDate
print(t3-t2) //->14.2085000276566
(Do not try to test the code above in the Playground. The numbers are taken from a single trial executed as a CommandLine app.)
How to convert a camel-case string to dashes in JavaScript?
You can use replace
with a regex like:
let dashed = camel.replace(/[A-Z]/g, m => "-" + m.toLowerCase());
which matches all uppercased letters and replace them with their lowercased versions preceded by "-"
.
Example:
console.log("fooBar".replace(/[A-Z]/g, m => "-" + m.toLowerCase()));console.log("FooBar".replace(/[A-Z]/g, m => "-" + m.toLowerCase()));
How to convert a string to camelcase in Google Spreadsheet formula
This should work:
=JOIN("",ArrayFormula(UPPER(LEFT(SPLIT(A3," ")))&LOWER(MID(SPLIT(A3," "),2,500))))
or to be more precise:
=JOIN("",ArrayFormula(UPPER(LEFT(SPLIT(A3," ")))&LOWER(REGEXEXTRACT(SPLIT(A3," "),".(.*)"))))
CamelCase to underscores and back in Objective-C
Chris's suggestion of RegexKitLite is good. It's an excellent toolkit, but this could be done pretty easily with NSScanner. Use -scanCharactersFromSet:intoString:
alternating between +uppercaseLetterCharacterSet
and +lowercaseLetterCharacterSet
. For going back, you'd use -scanUpToCharactersFromSet:
instead, using a character set with just an underscore in it.
What is the difference between combining array by using reduce or joined?
There are two reasons why joined
is a better choice than reduce
:
Readability
If you want to join multiple strings into one string, why would you use
reduce
, with manual concatenation? If there is a specific function for the task you want to do, use it. When reading the code, it's easier to understandjoined
thanreduce
.Performance
joined
forString
can be implemented better thanreduce
. It does not have to be but it can.reduce
operates on one element at a time, without knowledge about the other elements, with many temporary variables passed around.joined
has the knowledge of the entire sequence and it knows that the operation is always the same, therefore it can optimize. It can even use the internal structure ofString
. See String.joined implementation.
In summary, always use the more specific implementation.
Note that the performance reason above is the less important one.
Related Topics
Exc Bad Access While Creating a New Characterset
Alamofire Request Not Working in Swift 4 Project
Swiftui - How to Change The Button's Image on Click
Pass Custom Parameter to UIbutton #Selector Swift 3
<Unknown>:0: Error: Opening Import File for Module 'swift': Not a Directory
Comma Automatically Being Added to Textfield in Swift
Swift 4, Coreplot, Send Chart via Mail App (With Messageui)
Parse Nested Completion Handlers
Biometric Authentication Evaluation with Swiftui
Swiftui Navigationview Not See Image
Swift "Print" Doesn't Appear in Stdout But 3Rd Party C Library Logs Do When Running in Docker on Ecs
Rlmexception', Reason: 'Attempting to Modify Object Outside of a Write Transaction
How to Specify The Name of The Output Executable
List Scroll Freeze on Catalyst Navigationview
Cannot Convert Value of Type 'Nsmutablearray' to Expected Argument Type '[Skaction]'