📜 ⬆️ ⬇️

Classes in Swift [Part 1]

Recently, Apple introduced to the public a rather important change in the development of iOS applications, announcing a new programming language, Swift. Currently, the number of materials in Russian dedicated to this language is limited. Swift is also an object-oriented language, and the classes in it are the basis of the basics. So I decided to translate this article.



Creating classes


To create new classes, use the class keyword, the class name and curly braces, inside which the properties and methods of the class are declared.
 class Point { var x = 0.0 // sets the default value of x to 0 var y = 0.0 // sets the default value of x to 0 } // this creates a new Point instance using the default initializer var point = Point() point.x = 100 // sets the x property to 100 point.y = 200 // sets the y property to 200 


Initializers


From Apple's official documentation :
Initialization is the process of preparing an instance of a class, structure, or enumeration for further use. It includes the initialization of each property and the execution of other settings or initializations necessary before the first use.
')
The initialization process is implemented using initializers, which are special methods that are called when declaring new instances of a class. Unlike Objective-C, initializers do not return anything in Swift, since they ensure that new class instances are initialized correctly.

Let's look at an example
 class Point { var x var y } 

Running it will give you three compilation errors.
 class Point { // Class 'Point' has no initializers ( <code>Point</code>   ) var x // Type annotation missing in pattern (  ) var y // Type annotation missing in pattern (  ) } 

To fix this, let's set the type of each property.
 class Point { var x: Double var y: Double } 


The initializer is specified by the init keyword. An initializer may have several parameters, or there may not be any at all.
 class Point { var x: Float var y: Float init(x: Float, y: Float) { self.x = x self.y = y } } // Example usage var point = Point(x: 100, y: 200) 


We can also set optional property values. To do this, just put it ? after the type as shown in the example. If you declare a property in this way, it will have a default value of nil .
 class Point { var x: Float? var y: Float? } var point = Point() // both the x and y properties are now set to nil point.x = 100.0 point.y = 200.0 


Initializers overload


Imagine that during the creation of a project it became necessary to use a list of users. Let's first create the User class. Each class object will have the following fields: first name ( firstName ), last name ( lastName ), brief information about the user ( bio ). The first and last name fields will have optional values, and the brief information field will have a default value (that is, this field will be optional).
 class User { var firstName: String? var lastName: String? var bio: String = "I ♡ Swift!" } var user = User() // user = { firstName: nil, lastName: nil, bio: "I ♡ Swift!"} 


Well, the class we wrote. Now it's time to create the first users. The summary information field is optional, so we need to overload the initializer, since you can either write something about the player, or leave him a dark personality. Well, let's write initializers for both cases:

 class User { var firstName: String var lastName: String var bio: String = "I ♡ Swift!" // no bio provided init(firstName: String, lastName: String) { self.firstName = firstName self.lastName = lastName } // bio provided init(firstName: String, lastName: String, bio: String) { self.firstName = firstName self.lastName = lastName self.bio = bio } } var me = User(firstName: "Andrei", lastName: "Puni") // me = { firstName: "Andrei", lastName: "Puni", bio: "I ♡ Swift!"} var silviu = User(firstName: "Silviu", lastName: "Pop", bio: "I f**ing ♡ Swift!!!") // silviu = { firstName: "Silviu", lastName: "Pop", bio: "I f**ing ♡ Swift!!!"} 


However, you see, this is not entirely rational, because the differences in initialization are minimal — there is some information about someone, but not about someone. Therefore, let's write one initializer, and give the bio argument a default value.

 class User { var firstName: String var lastName: String var bio: String init(firstName: String, lastName: String, bio: String = "I ♡ Swift!") { self.firstName = firstName self.lastName = lastName self.bio = bio } } var me = User(firstName: "Andrei", lastName: "Puni") // me = { firstName: "Andrei", lastName: "Puni", bio: "I ♡ Swift!"} var silviu = User(firstName: "Silviu", lastName: "Pop", bio: "I f**ing ♡ Swift!!!") // silviu = { firstName: "Silviu", lastName: "Pop", bio: "I f**ing ♡ Swift!!!"} 


Class identities


From Apple's official documentation :
Identity operators

Since a class is a reference type, a situation may arise where the same instance of a class is denoted by several variables or constants. (This is not possible for structures and enumerations, since both are meaningful types and are copied when assigned and passed to a function as parameters)

Sometimes it is useful to find out that two variables or constants refer to the same instance of a class. There are two operators for this in Swift:
Are identical ( === )
Not identical ( !== )

Suppose we have a list of players, one of them is the owner of the castle. We need to add some features for players who are not owners of the castle. To do this, let's use the identity operator ( === )
 var users: User[] = [ ... ] // User[] means Array of Users var host = /* some user */ for user in users { if user === host { // host logic here println("this is the host") } else { // guest logic here println("this is a guest") } } 


The equality operator ( == ) does not work when comparing class objects, so you should not be afraid of such errors.

In the next section, we will look at class inheritance and protocols.

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


All Articles