As Swift nears the end of it’s beta, some patterns and trends have emerged for better and worse. All languages succumb to division and preferences in the community, thus it is important to rally behind standards and to create and use tools to help others adhere to these standards. This post will be an organic list of updates and best practices as deemed fit by the creators of the SwiftCast website. It’s very opinionated and biased, but not without reason. We hope that in time the community will create better tools and standards over time, and we highly value feedback, critique or praise to opinions shared in this post.
Generics in Swift are very useful. The help you write abstract and highly reusable code allowing you to stay DRY and define your own requirements. However, this flexibility also gives you just enough rope to hang yourselves with and as such it is always better to be specific about the types your code expects to receive and work with.
Swift defines two type aliases for non-specific types: Any and AnyObject. An instance of any class type can be represented by AnyObject while Any *can represent any data type. This can be useful when actually needed. For example, in the Swift standard library an obvious and useful use of generics are *Array and Dictionary. Both data types are collections of generics, so for example, an Array of Int values can exist and so can an Array of String values. Generics are also often encountered when dealing with Cocoa API’s due to the fact that Objective-C does not provide explicitly typed arrays like Swift.
Given the fact that generics are indeed useful, they should only be used when truly necessary or especially useful. It is also important to provide good comments or documentation wherever generics are used so that another developer can understand what good code should look like.
This one is easy to demonstrate. Just take a look at one line of code and try and identify the variable type:
let show = slidersEpisode()
Type Inference in Swift can be a great thing when the data type is obvious such as:
let show = "Season 1, Episode 5"
When type cannot be obviously figured out with definition, it is often better to be explicit:
let show: String = slidersEpisode()