This repository was archived by the owner on Sep 3, 2018. It is now read-only.
forked from hebertialmeida/ModelGen
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFilters.swift
56 lines (51 loc) · 1.9 KB
/
Filters.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//
// Filters.swift
// ModelGen
//
// Created by Heberti Almeida on 2017-05-15.
// Copyright © 2017 ModelGen. All rights reserved.
//
import Foundation
/// Convert string to TitleCase
///
/// - Parameter string: Input string
/// - Returns: Transformed string
func titlecase(_ string: String) -> String {
guard let first = string.unicodeScalars.first else { return string }
return String(first).uppercased() + String(string.unicodeScalars.dropFirst())
}
/// Generates/fixes a variable name in sentence case with the first letter as lowercase.
/// Replaces invalid names and swift keywords.
/// Ensures all caps are maintained if previously set in the name.
///
/// - Parameter variableName: Name of the variable in the JSON.
/// - Returns: A generated string representation of the variable name.
func fixVariableName(_ variableName: String) -> String {
var _variableName = replaceKeywords(variableName)
_variableName.replaceOccurrencesOfStringsWithString(["-", "_"], " ")
_variableName.trim()
var finalVariableName = ""
for (index, var element) in _variableName.components(separatedBy: " ").enumerated() {
element = index == 0 ? element.lowerCaseFirst() : element.uppercaseFirst()
finalVariableName.append(element)
}
return finalVariableName
}
/// Cross checks the current name against a possible set of keywords, this list is no where
/// extensive, but it is not meant to be, user should be able to do this in the unlikely
/// case it happens.
///
/// - Parameter currentName: The current name which has to be checked.
/// - Returns: New name for the variable.
func replaceKeywords(_ currentName: String) -> String {
let keywordsWithReplacements = [
"class": "classProperty",
"struct": "structProperty",
"enum": "enumProperty",
"internal": "internalProperty",
"default": "defaultValue"]
if let value = keywordsWithReplacements[currentName] {
return value
}
return currentName
}