Classes in Swift [Part 1]

Original author: Andrei Puni
  • Transfer
  • Tutorial
Recently, Apple introduced to the public a fairly important change in the development of iOS applications, announcing the new programming language Swift. Currently, the number of materials in Russian devoted to this language is limited. Also, Swift is an object-oriented language, and the classes in it are the foundation of the basics. So I decided to translate this article.



Class creation


To create new classes, use the keyword class, class name, and braces, inside of which class properties and methods 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 the official Apple documentation :
Initialization is the process of preparing an instance of a class, structure, or enumeration for future use. It includes the initialization of each property and the execution of other settings or initializations necessary prior to first use.

The initialization process is implemented using initializers, which are special methods that are called when new instances of the class are declared. Unlike Objective-C, in Swift initializers do not return anything, because they ensure the correct initialization of new instances of the class.

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

By running it, you get three compilation errors
class Point { // Class 'Point' has no initializers (класс Point не содержит инициализаторов)
    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 keyword init. The initializer may have several parameters, or it may not be 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, simply put ?after the type, as shown in the example. If you declare a property in this way, it will have a default value 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


Initializer Overload


Imagine that during the creation of the project it became necessary to use a list of users. Let's create a class first User. 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 (i.e. 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, we wrote a class. Now it's time to create the first users. The field of brief information is optional, which means we need to overload the initializer, because you can 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 must admit, 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 biogive the 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 Identity


From the official Apple documentation :
Identity Operators

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

It is sometimes useful to find out that two variables or constants refer to the same instance of the class. There are two operators for this in Swift:
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 part, we look at class inheritance and protocols.

Only registered users can participate in the survey. Please come in.

Is translation useful for you?

  • 57.6% Yes, the translation was useful 174
  • 9.9% No, translation is useless 30
  • 9.9% I can not answer unambiguously 30
  • 22.5% Not Interested in Swift 68

Also popular now: