Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Adding initializers to a class

Using dictionaries Использование словарей | Understanding tuples | Understanding tuples Понимание кортежи | Creating optional variables | Creating optional variables Создание дополнительных переменных | Defining and using enumerations | Defining and using enumerations | Writing closures | Writing closures Написание закрытия | Defining and instantiating classes |


Читайте также:
  1. Adding a New Controller
  2. Adding a Pump to the Diagram
  3. Adding initializers to a class Добавление инициализаторами к классу
  4. Adding property observers
  5. Adding property observers Добавление наблюдателей собственности
  6. Classical Champion of Free Trade

 

- While we can provide initial values for every single one of our properties, an alternative is to add an initializer to your class. A way of providing custom functionality that will automatically be called when a new instance is created. So, I'm beginning here with a basic class definition. I'm going to removed the initial values for both of these properties this string and the integer. As soon as I do this, I'm going to see an arrow pop-up. I can not right now instantiate objects of this class, because they might exist in an invalid state.

That's okay, I'm going to add the initializer now. So, it's just init and a code block and the empty parenthesize. This is the default initializer. It takes no perimeters, and Swift initializes do not return anything, so we don't see the return arrow here. It's like a method just called init, but we also don't need the funk keyword in front of it. It is a reserved keyword. This is understood by Swift. So, I'm going to use this to set a couple of default valleys for my two properties. So, name equal to John Doe, and score is equal to zero.

Now the arrow goes away. It is understood that this class is valid. I can instantiate this. When we do this, the init method is going to be called automatically. So, if I show the contents of this, we will see that in description. It's got that internal state. Player John Doe has a score of zero. So, moving on. If I wanted different values, if I didn't want to just accept these defaults, well, I could create the object like this, and then change its properties. If I want the option to create and initialize a new player object with different data from this default, well, I could make a custom initializer.

An initializer that accepts perimeters. So, I'll go ahead and do that an initializer with perimeters. We're still using init, except this time instead of empty parenthesis, I'm going to say name colon string. Now, we run into a problem, and that name is also a property of this class. So, if I'm wanting to accept this perimeter in and use it to set the property, well, I can't really just write name equals name. We've got kind of an issue there. I have to be explicit about this. So to avoid collisions, I could either change the perimeter name, but a better way is just that I'll do this. Self.name.

Use the (forward) self meaning the current instance of this class. To make it very clear, when I'm referring to a property of this class self.name as opposed to just a perimeter being past in. Other languages use this or me to refer to the same idea the current instance of this class. Swift uses self. It's true we don't always need to use self. I didn't have to use it here for the score property, but it is good practice for clarity, if there's any possibility for misunderstanding as to what you're referring to.

All right, so we now have two initializers. If I leave the original init method in this class, I now have a choice of either instantiating an object using the empty parenthesis like this, or instantiating by passing in a value with this new initializer. So, just creating a couple of new lines of code, using the custom initializer will create second player equal to player name:Alice. Then, I'll print out Alice's description. So, we can use the version with the empty parenthesis, which will set it to John Doe, or we can use the version passing in some information.

Now notice that I do need to provide a named perimeter here. If I had attempted to leave that out and just pass in a string literal value, I'm going to see the little arrow pop-up here. Although it's pretty obvious what this is, so it should suggest a fix it. Yes, the missing argument label name, so fix it just insert name, and it'll fix it for us. So, two separate object each with its own set of data, but created using different initializers. Now just as initializers are automatically called when an object is instantiated, we also have the option to create a de initializer, that is automatically called when an object reaches the end of its lifetime.

This is just a word de init with a code block. Now, you can only have one de initializer, and it isn't customizable. This takes no perimeters. It doesn't have any parenthesis. It returns no values, but this is where you would put any necessary cleanup code an object needs to do. Now in general, while initializes are very common, you do not need de initializers for the majority of your classes. It's only needed in situations like having a class that opens a connection to a database or file when it's first instantiated.

It keeps that connection open through the lifetime of the object, and you need to make sure that object has closed the connection to that resource before it's de-allocated. Most of the time, you do not need a de init. Now, calling de init is not under your direct control. You don't actually do it yourself. In Swift, we don't do manual memory management. Swift uses something called automatic reference counting or ARC. While we do manually create our objects when we decide to instantiate them here, whether it's using a normal init method or an overloaded one, we are deciding to create that object.

We say whether instantiated, but Swift keeps track of when these objects are no longer needed. It will decide when to de allocate them, and at that point is when the de init would be called. Now bear in mind, if you have a class that does hold open a resource, there's nothing to stop you writing your own method that preforms any necessary cleanup. Just calling it yourself within the normal logic of your programming, that is what you typically should be doing. You don't need to leave it to de init, but you can use de init to ensure that cleanup has happened.

 

 


Дата добавления: 2015-08-20; просмотров: 80 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Defining and instantiating classes Определение и создание экземпляра классы| Adding initializers to a class Добавление инициализаторами к классу

mybiblioteka.su - 2015-2024 год. (0.007 сек.)