3 ms·
Surprised to see this opinion on `guard`! IMO it's such a nice feature for future developers looking at that code, it's a clear indicator to pay attention to th
by myko 4y ago
Surprised to see this opinion on `guard`! IMO it's such a nice feature for future developers looking at that code, it's a clear indicator to pay attention to this area of code and know exiting the function is important.
- msie 4y agoI may be too harsh on guard but I like small languages. When I first encountered guard I wondered if it was truly necessary to the language and it wasn't.
- dagmx 4y agoMany languages have ergonomic features that aren’t truly necessary but are worth having. I recognize you prefer smaller languages but I’d like to make a case for guards usefulness. Guard is great because it’s a combined early return and assignment. Imho if you have a language with optionals, it’s a required pattern to have, or you end up with lots of conditional unwraps and nested blocks, or lots of placeholder variables that you might accidentally use in your code later causing safety or memory access issues . Take the following code if let foo = Some(optional) {yourLogicHere} else {return} That’s one level of nesting. Swift is nice enough to elide the Some matching so you’d just have if let foo = optional {yourLogicHere} else {return} Still one level of nesting but a little cleaner. Now if you have a language based around safety, like Rust or Swift, a lot of functions return optionals. So you’ll keep nesting code in your checks for safety Now take a guard. guard let foo = optional else { return } yourLogicHere That’s one level of unnesting removed , and that compounds. Better yet, you can chain them guard let foo = optional, let spam = foo.lookup() else {return} The equivalent in C like languages would be type foo; if (!getOptional(&foo) return; Now either you early return in the case of the optional failing or you nest. Nesting gets repetitive and deep. Or you unnest like I have and have that foo sticking around un-initialized, potentially causing issues of use later. Guard simultaneously removes both conundrums and makes your code both neater and safer.
- O-stevns 4y agoAdding to this excellent explanation, the guard is compile time checked too, so you can't accidentally screw up the early return like one could in say c or c++ It might seem like a quality of life feature to some, to me however it's an essential feature of swift and one of the better ones.