📜 ⬆️ ⬇️

Three bugs iOS developer, which can be costly



Creating an iOS application is not an easy task. Developers want to complete this process as quickly as possible and finally run in the AppStore. But this does not end there: the creators have for many years correcting errors, improving functions and working with other developers. We would like to make life a little easier for them and for this we decided to sort out three things that should be avoided during iOS development (thanks to Envato Tuts + for the information).

1. Constants, constants ... me and with variable norms


At first glance, variables are more universal than constants. But if you can use a constant, then it is better not to resort to variables. Constants have several advantages.

Readability


This is perhaps the main advantage. Suppose you are writing an e-commerce application for the USA. Specify the local sales tax rate - 8.75%. And at this moment conditional Vasya, who does not know anything about the sales tax, is connected to the development.
')
If you enter a variable to indicate the sales tax rate, it can change it literally with a single line of code, which can seriously harm the application. If you change the keyword from var to let , the compiler will report that this value cannot be changed, and Vasya will remove his fateful fingers from the keyboard.

Reference to value


With the help of let you can refer to any value in the code. You create the application, create it and suddenly, following the example of the Rolling Stones, you decide to paint everything black. If you have registered a constant, then if you change it in one place, all other references to color will also change. And if not, then you have to look for and change everything manually.

Instantiating a class or structure


If you are creating a singleton, you need to create a shared instance of the class. This is usually done through a static let declaration inside a class declaration. After that, you give a name to a constant, assign it to an instance of a class, and you can safely use it throughout the application.

If you need to create an instance of a regular class (say, in ViewController.swift), you create a constant and assign it to an instance of the class you need - this creates a link that you can easily use throughout the file. Constants are back in business!

As you can see, constants have many advantages. They increase the readability of the code, they are useful for storing immutable values ​​and, of course, not as useless as you think. Cool developers love constants and change them with variables only if there’s no way to change the values.



2. Bang Operator! How cool it sounds, what is needed for the optional!


Options is a very powerful feature of Swift. These are types a la int and String , annotated with a question mark after the type declaration. If you want to declare a variable as an optional string, you can simply write:

 var someVariable: String? 

This is a signal to the compiler that there will either be a value in it or not. String? and String are considered two different types.

The optional is a gift box. This box may or may not store the value. If you want to know this, you need to optionally deploy. This is done in different ways.

Wrong: Forced Unwrapping (Forced Extract Value)


This operation (performed with an exclamation mark) is called a Bang Operator. We do not advise her to use. If the value of the optional extracted in this way is nil (nothing), then the application will crash. For example, like here:

 var someVariable: String? var somethingElse: String = "hello" func setupApp() {    self.somethingElse = self.someVariable! } 

In this example, the application will crash because we have not defined the value of someVariable and are trying to assign it to a variable of type String. The optionals were created to protect against such errors, and we are reducing all their efforts.

Correct: Optional Binding


This is one of the most popular options for working with optionals. You simply assign an optional value to a constant using an if statement. If you can retrieve a value from an optional value, the compiler is included in the closure, and you can use the created constant. Otherwise, you go to the else branch and pretend that nothing happened.

For comparison, take the same example:

 var someVariable: String? var somethingElse: String = "hello" func setupApp() {    if let theThing = someVariable {        self.somethingElse = self.someVariable!    } else {        print("error")    } } 

With the optional binding, the compiler does not crash the entire application, but quietly enters the else branch and prints an “error”.

And again correctly: Optional Chaining (optional chain)


Another common way to safely retrieve an option is an optional chain. So you can completely avoid nil values ​​with just one line. If at some point such a value is obtained, this line of code simply stops executing. For example:

 var someClass: SomeClass? = SomeClass() var somethingElse: String? func setupApp() {    self.somethingElse = someClass?.createString() } 

If someClass is nil, then the entire line will not be executed, the value of somethingElse becomes equal to nil. If the value is different from nil, as in the example above, then it is assigned to the variable somethingElse. In any case, the application will not fall.

And again true: Nil Coalescing (Combine Operator by nil)


This method allows you to process options in a single line, but unlike the method above, you must specify a default value or “else”. That is, for the scenario when the optional is nil). For example:

 var someVariable: String? var somethingElse: String = "hello" func setupApp() {    self.somethingElse = someVariable ?? "error" } 


It looks mysterious, but the essence is simple. If the expression on the left has any value (that is, not equal to nil), then that value will be used. If the value is nil, then the default value will be used - in this case, the hard-coded string. The expression on the right must be different from nil, and its type must be non-optional — otherwise the whole meaning is lost.

3. Leave all these architecture patterns for later


And finally, a classic mistake. Many people do not structure the code, which causes sustainability, efficiency and the ability to support it in principle. You can squeeze all your code into the ViewController classes, but this rash step will be shed in flammable tears when you have to change and debug the code.



Code is the foundation on which you develop your application. Without a consistently laid foundation, the multi-storey building of your application will collapse easily. The foundation of an iOS application is the selected design pattern. Consider the two most commonly used templates.

MVC (Model-View-Controller)


The Model-View-Controller , or MVC, design pattern divides each part of your code into three parts: model, view, and controller.


There are many variations of MVC, for example, MVVM and MVP. It is worth reading about them, but the principle of their work is similar to MVC, therefore we will not dwell on them here. All of these are design patterns that make our code modular.

Singletons


Singleton is the only instance of a class that is always present in memory. And what is special about it? Suppose you create an application that connects to the database, and you need to put all the connections somewhere. Singltons are perfect for this. Here's how to create them:

 // Declaration class DataService {    static var shared = DataService()        func createUser() {    } } // Call-site DataService.shared.createUser() 

If you follow these simple tips, the application will be easier to maintain and you will find errors faster than customers.

All the errors we have considered perfectly illustrate the old Russian wisdom: "If you go slower, you will continue." We hope that the article was useful, and we expect that you will also tell us how some pitfalls of iOS development were avoided. We promise a nice gift from the EFS Program to the author of the most original story!

Source: https://habr.com/ru/post/340736/


All Articles