11 tips to level up your Swift programming skill

Hari Krishnan
10 min readJun 12, 2021

Programming has been constantly evolving from the day programmers started using it and a standard and structured way of programming is imperative not only for the efficacy of it but also for better readability which can in turn help developers to maintain it. The standard of coding that apple expects from its developers is a cut above and probably that could be the reason what finally delivers exceptional user experience to its users. Over the last decade, iOS has been providing various cutting edge functionalities with an eye to its users. The leveraging of such features with a user centric approach is paramount as far as its developers are concerned and it can only be done with standard & clean coding which adapts the latest programming methodology.

Swift is a magnificent, powerful & intuitive programming language designed by Apple for iOS, iPadOS, macOS, tvOS, and watchOS. It is a product of Apple’s engineering sagacity and diverse contribution from its open source development community which gives predominant considerations to modern language thinking. In this article we discuss 11 various tips that can level up one’s swift programming competency and thereby performance of applications.

1. Enums with Asserted values

Consider a struct that can be used for holding both article & video metadata. It has a mandatory type & title where type is an enum which can either be an article or a video. In addition to that, there are two optionals such as duration and letterCount where duration is imperative for videos and letterCount is vital for articles. This is obviously not a great way of implementation as duration is unnecessary for articles and letterCount is not useful for videos. Even in such conditions, the objects had to bear an extra irrelevant parameter with them for the sake of a common Content struct. This condition can be avoided using Enums with asserted values.

A typical example of Enum with asserted values

In the above code snippet, there are two cases with which they are asserted with values. Hence, they are known as enums with asserted values. Here, an article case only allows title and a letter count and it does not accept a duration parameter. On the other hand, a video case only allows a title and a duration and it does not accept a letterCount. By this way, we can not only avoid an extra unwanted property but also make it type-safe.

2. Final and Private

The compile time & app’s performance can significantly be improved by using access modifiers final and private for one’s classes and properties where it makes sense.

Class with final keyword

If you create a class that doesn’t require to be subclassed, then mark it as ‘final’ . If you want it to be subclassed in the future you can just take out the key and subclass it.
As far as the properties are concerned, if they are only going to be accessed with in the code you write inside that class then mark it as ‘private’.

Class with private property

3. Use let instead of var

Consider the below code snippet that is used for making a network request using URLSession.

A snippet that uses variables in a network request method

let is used for creating constants in swift where as var is used for variables. Here in this executeNetworkRequest method, everything is made using var. In this method, none of them are going to change in the future, so it is always advisable to keep them as constants.

A snippet that uses constants in a network request method

Here, the point is when you change a var to let the compiler understands that it is a constant and is not going to change in the future. This gives the compiler some more room to do some optimisation. In addition to that, in future, it would be helpful for developers to understand that the value of an item is not going to change and there by it gives better readability. It is critical when it comes to convoluted functions where execution goes in different directions and if the developer knows that some of those items are not going to change in the remaining portion of execution, it helps him or her to update it if they want.

As far as the modern programming theories are concerned, particularly in the aspect of functional programming, immutability is a vital aspect that enhances the run time efficiency as well as readability. If you use constants everywhere, you know for sure that your data can’t be changed by surprise by some other part of your program — in fact, it can’t be changed at all. This also makes multi-threaded code significantly easier to think about.In addition to that, swift can optimise the code more efficiently. If Swift knows a value can’t be changed, it can in theory store your data in a more efficient way.

4. Computed properties

Traditional way

Have you ever tried methods like above for simple calculations & conversions? Instead of using a method for doing it, you might be able to use a computed property where the value of that property is calculated on the fly. Computed properties do not store values in them. Instead, they calculate it after executing some code.

Using computed properties

5. Use Higher functions like filter, map, reduce

Older way to filter elements from an Array

Consider the above snippet of code. A person who is not proficient in writing idiomatic swift codes might be calculating the multiples of 3 from an array like this. Here, a variable array called ‘oddOnly’ is initialised and the execution iterates each element of the array using a for loop and checks whether it is a multiple of 3 and if it is correct, adds that element to the ‘oddOnly’ array. This is the old an in efficient way of accomplishing the task as it not only supports immutability but also needs to update the variable array whenever it finds a match. This can hamper the performance significantly when it comes to larger arrays and the execution has to perform all these lines of codes as well.
Instead of following these kinds of archaic approach, a developer can use higher order functions to accomplish these tasks more effectively.

Higher order functions in swift example

The above snippet of code uses filter method for identifying the multiples of 3 and assign those filtered values to an immutable (let) array which is ‘oddIntegers’. No code iteration is required and no variable array updates are happening in this case. This will not only enhance the performance but also limit the number of lines of code that can provide better readability. Like that, ‘integerSquares’ array holds the squares of each elements in the ‘integers’ array and constant ‘totalSum’ holds the total sum of elements of ‘integers’ array. Both of them save a huge amount additional execution time as well as a number of additional lines of codes.

6. Provide default values for parameters

If you want to provide an option for a parameter in a method, you can do it by providing a default value for that parameter. Consider the below example.

Passing default value for a parameter in Swift

Here, a method called ‘makeFriedRice’ which accepts its flavour as a parameter. Enum ‘Flavour’ which contains three values which are spicey, tomato and normal. As you can see, this method can be called with or without flavour. By default, the flavour would be normal if no value is provided. This method can be called with or without passing the parameter. If default value is not provided, then the compiler would throw an error message. So in a method if a parameter can hold a default value, consider to provide it so that the method can be called without it as well. This default value can also be nil, if no value could be there for that parameter.

7. Use Extensions

Another significant way to organise your code is by breaking it up using extensions. As far as the swift documentation is concerned, Extensions add new functionality to an existing class, structure, enumeration, or protocol type. Using Extensions you can add properties, methods, conforming to protocols etc. Hence, you can move part of your code to extensions if it logically makes sense.

Usage of extension in TableViewController

In the above code snippet the datasource methods associated with the tableview are implemented in the firstViewController extension so that they will not be mixed up with the actual business logics and other remaining functionalities.

8. Maintain a constant file for hardcoded strings

This is another effective way to organise your code and transform it into a lot more professional codebase. By centralising all hardcoded strings in a common file will help you to manage them properly by replacing the values only at one place so that it will be reflected in all other parts of your source code rather than changing it where ever they are used. This can be implemented by creating a swift file for keeping these constants.

Swift file for maintaining Constant String values

The above code snippet shows the way hardcoded strings are maintained in swift file. A struct named ‘Constants’ is declared and all hardcoded strings can be added in it as static constants and the nested hardcoded values can also be given by declaring another struct inside it. By this way, all hardcoded string values can be configured in a single swift file and can be accessed anywhere.

A ViewController which accesses Constants that are declared in ‘Constants’ struct

These hardcoded values can be accessed like in the above snippet.

9. Short hand if statements

Use short hand if statements wherever possible. If-else ladder statements make the program convoluted in most of the cases and it is a conventional way of writing the logics in a program. Too many usage of such if else conditions would make the program difficult to follow and such problems can be resolved using the contemporary short hand if statements.

A typical if else statement ( Figure A)
Short hand if statement ( Figure B)

Here in Figure A, while following the conventional way, developer had to create a variable called ‘message’ and implement if else conditions where in Figure B he or she was able to accomplish the same with a single line of code and by using a constant called ‘message’.

Figure C
Figure D

The ladder of menacing if statements which are provided in Figure C , can be avoided by joining those conditions in a new way which is shown in Figure D. Here it is done by using a ‘ , ’ between conditions which in this case is equivalent to ‘&’ operator. In this case ‘ , ’ can be replaced by ‘&’ operator because the values of these conditions are boolean but the return value may not be boolean in all conditions. Consider if let statement for instance, the return of if let is always a boolean but there is also an unwrapping. Hence an ‘&’ operator cannot be used instead of ‘ , ’ in all cases.

10.Use Nil coalescing operator

Figure A

In the above code snippet, a variable ‘myCusine’ is assigned as ‘favouriteCusine’ only if ‘favouriteCusine’ optional e holds a value or it will be assigned as “N/A”. This can easily be re-written using Nil coalescing as provided below.

Figure B

By following the above method, not only the number of lines can be significantly reduced but also a constant can be used instead of a variable.

11. Use Optional binding with the constant name is the same as the optional name

Figure A

In the above code snippet, ‘myCuisine’ is an optional and there is another name ‘cuisine’ is used in the if let statement. Instead of this, the same name ‘myCusine’ can be used in the optional binding so that we can avoid an extra name.

Figure B

In the above snippet, the same name ‘myCusine’ is used for constant to unwrap ‘myCusine’ optional. By this way an extra name can be avoided. This will, in turn, reduce significant amount of confusion.

Conclusion

The points provided above are beneficial for swift programmers to organise and write their code in a structured and efficient way. Adapting such concepts and methodologies will not only reduce the development time significantly but also catalyse the performance of applications.

--

--

Hari Krishnan

Senior Mobile Technical Lead at Marlabs Inc. Have greater expertise in Swift,Objective-C,ReactNative, Kotlin, Javascript & React JS, IoT, VR & ML