Swift VI

Introduction

A few new cool discoveries in Swift today! I’m really glad I follow some insanely cool people on twitter, since that’s how it all started.

Swifty Swift

All the tips and tricks that I came across are mostly about making the most out of the language, and using very convenient and readable practices, so here it goes:

Enum All The Things

Enums in swift are over-powered, which makes them awesome. A few important enum features include:

  1. Associated values
  2. Extensible with functions and initializers
  3. Delightful shorthand syntax
  4. Much more..

Now, I’d like to focus on a specific use case for enums that I came across here.

Here is the gist:

enum Result {
    case Success(String, String)
    case Error(String)
}

let success = Result.Success("3AFG09X", "More info here")
let failure = Result.Error("Could not synthesize a potion.")

switch success {
case let .Success(value1, value2):
    let displayString = "We have \(value1) and \(value2)."
case let .Error(error):
    let displayString = "Something went wrong :( .. \(error)"
}

Why is this so darn convenient?

For starters, it allows us to group all related “result” semantics together in a single type. Within that type, we can define the error messages, as well as success handlers. For better decoupling of error handling, it can also operate on an external error handler without problems. The point being, you go to that single enum to understand all what you need about results your getting from a certain call.

For Framework designers, this is a godsend. By using such pattern, you effectively deliver all your possible outcomes from an API call in a single place, conveniently referenced by the user.

Inner Classes

An inner class is a class defined within a closure, and can only be instantiated by that closure, or something. I didn’t understand this concept quite well, and didn’t really research it, but hey! It sounds awesome.

Conclusion

Knowing that a language has certain features, and properly making use of the features are two completely different things. Just don’t forcefully use a feature just for hipster-sake, but also, try playing with it in playgrounds so you’ll actually remember it when you need it!