Some Tips to Improve Your Code (Swift)

Tram Ho

Table cheat useful iOS dev tips; enums, options, ternary operators, and more

I’ve compiled a cheat sheet of some of the useful Swift tips and tricks that we use to create our iOS apps. I hope that you can find something useful on this list, if you have any suggestions or find any issues, feel free to let me know.

1. Optional Unwrapping

Unwrap optional variables and handle all errors in one line with option 2. If both option values ​​do not have a value equal to nil, the function will continue our lower processing section (Reached). If either of these variables is nil, they will go back and exit the scope of this function.

2. Ternary Operators (Triad operator)

Compress your conditional logic into a line with these useful operators. Set the value of a variable depending on the state. Also, you can nest these operators neatly, if it’s a little hard to read the code.

3. Generics

Programming generics, as defined by Google, is a method for writing functions and data types while making minimal assumptions about the type of data being used. Using generics allows abstraction to create cleaner code with fewer errors. As you can see, by selecting option 2, we can write a function (compared to many) that can handle several different types of inputs.

4. Generate a UIColor via Hex Code

Create the file name UIColor + Extended.swift that contains the following code:

Wow, now we can create color through hex code, like this:

5. Use Extensions

Create a single class extension file that you frequently reuse. In this case, I chose UIButton to demonstrate additional custom click functionality. Now, wherever we add a UIButton, we can call the press function to mimic an output animation into the scale, like this:

6. Funnel Multiple Back-End / Function Calls through a class

Imagine you have a function you need to call inside your application to update your local data like this:

In this example, FAB represents Google Firebase. Now imagine we want to tear down Firebase and replace it with an alternate back end, this tip will create such a quick and simple scenario. When you’re writing code, if you find yourself making some calls to the same function on your application, create a class that Funnel Sketches your calls into as a function, then calls your network code. friend. For example:

In option 1, if we want to replace Firebase, we will need to make three calls. In option two, we only need to update the network class.

7. Guard Let

Using protection statements is more useful for than just unpairing options. You can use these statements to check conditional authentication, simply to move the program control out of scope under certain conditions. For example:

Temporarily let me end here. Hope can help you better code. Wait for part 2 with me.

References: 15 Quick Tips to Improve Your Swift Code

Share the news now

Source : Viblo