Skip to content

Instantly share code, notes, and snippets.

@joemasilotti
Last active November 17, 2015 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joemasilotti/45359df850cf717c6289 to your computer and use it in GitHub Desktop.
Save joemasilotti/45359df850cf717c6289 to your computer and use it in GitHub Desktop.
Which Swift guard formatting do you prefer?
//: 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
Copy link

guard let
    name = info["name"] as? String,
    age = info["age"] as? Int
else {throw Error.ParsingError}

@joemasilotti
Copy link
Author

@Jessy- awesome! Just updated the gist.

Now if only Xcode would auto format that else statement to line up with guard.

@worthbak
Copy link

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