Last active
November 17, 2015 15:46
-
-
Save joemasilotti/45359df850cf717c6289 to your computer and use it in GitHub Desktop.
Which Swift guard formatting do you prefer?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
enum Error: ErrorType { | |
case ParsingError | |
} | |
struct Person { | |
let name: String | |
let age: Int | |
init(name: String, age: Int) { | |
self.name = name | |
self.age = age | |
} | |
} | |
func parseGuardOneLine(info: [String: Any]) throws -> Person { | |
guard let name = info["name"] as? String, let age = info["age"] as? Int else { | |
throw Error.ParsingError | |
} | |
return Person(name: name, age: age) | |
} | |
func parseGuardMultipleLines(info: [String: Any]) throws -> Person { | |
guard let | |
name = info["name"] as? String, | |
age = info["age"] as? Int | |
else { throw Error.ParsingError } | |
return Person(name: name, age: age) | |
} |
JessyCatterwaul
commented
Nov 17, 2015
@Jessy- awesome! Just updated the gist.
Now if only Xcode would auto format that else
statement to line up with guard
.
Of the two examples (with multiple declarations), I definitely prefer the latter. For a single declaration, I prefer to keep things on a single line:
guard let data = dictionary where !data.isEmpty else { return nil }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment