Skip to content

Instantly share code, notes, and snippets.

@mattfenwick
Last active June 30, 2017 20:18
Show Gist options
  • Save mattfenwick/5b66c5e8af2f412a3eef4f8156baea75 to your computer and use it in GitHub Desktop.
Save mattfenwick/5b66c5e8af2f412a3eef4f8156baea75 to your computer and use it in GitHub Desktop.
iOS utils
{
"name": "X",
"fields": [
["a", "Int"],
["b", "String?"]
]
}
import sys
import json
# print 'args: ', sys.argv
# usage example:
# $ cat structexample.txt | python swiftstruct.py
infoText = sys.stdin.read()
# print infoText
info = json.loads(infoText)
structName = info['name']
instanceVariables = "\n".join([" let {0}: {1}".format(name, type) for (name, type) in info['fields']])
initializerVariables = "\n ".join(["{0}: {1},".format(name, type) for (name, type) in info['fields']])
initializerAssignment = "\n".join([" self.{0} = {0}".format(name) for (name, _) in info['fields']])
updateVariables = "\n ".join(["{0}: {1}? = nil,".format(name, type) for (name, type) in info['fields']])
updateReturn = "\n".join([" {0}: {0} ?? self.{0}".format(name) for (name, _) in info['fields']])
equatable = "\n".join([" guard lhs.{0} == rhs.{0} else {{ return false }}".format(name) for (name, _) in info['fields']])
formatString = """
struct {0}: Equatable {{
{1}
init({2}) {{
{3}
}}
// MARK: - updateValues
func updateValues({4}) -> {0} {{
return {0}(
{5})
}}
// MARK: - Equatable
static func == (lhs: {0}, rhs: {0}) -> Bool {{
{6}
return true
}}
}}
"""
print formatString.format(
structName,
instanceVariables,
initializerVariables,
initializerAssignment,
updateVariables,
updateReturn,
equatable)
import sys
# print 'args: ', sys.argv
name = sys.argv[1]
# generate default initializers for a xib-based view controller
output = """
class {0}: UIViewController {{
// MARK: boilerplate
// MARK: output
// MARK: ui elements
// MARK: private
// MARK: init
init() {{
super.init(nibName: "{0}", bundle: Bundle(for: {0}.self))
}}
required init?(coder aDecoder: NSCoder) {{
fatalError("init(coder:) has not been implemented")
}}
// MARK: view lifecycle
override func viewDidLoad() {{
super.viewDidLoad()
}}
}}
""".format(name)
print output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment