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

Using type properties and methods

Defining and using enumerations | Writing closures | Writing closures Написание закрытия | Defining and instantiating classes | Defining and instantiating classes Определение и создание экземпляра классы | Adding initializers to a class | Adding initializers to a class Добавление инициализаторами к классу | Using inheritance | Using inheritance Использование наследования | Creating computed properties |


Читайте также:
  1. A form of cryptosystem in which encryption and decryption are performed using the same key. Also known as conventional encryption.
  2. Answer the following questions using your own words but taking into account the
  3. Blocks on the webpage (properties are written in CSS file)
  4. C) Interview your partner using the questions in
  5. Choose a verb from the list and complete the text using Past Continuous or the Past Simple.
  6. Classification of phraseological units according to their contextual properties is suggested by
  7. Complete the following sentences using an appropriate form of the verb.

 

- The properties and methods we've created so far are instance-level properties and methods meaning that every object we create from a class has its own independent set of data and its own independent methods that act on that data. A change to a property of one instance or a call to a method of one instance does not affect any of the others. But we can also define class level or, in Swift, what are called type properties and type methods. They belong to the type itself, to our class, not to any one instance of that class.

So here's an example. I have a simplistic BankAccount class that I have created here, a few pieces of data, constants for accountNumber and routingCode. There's a variable for balance and interestRate and a few simple methods as well as an initializer, nothing special about any of this. So I have this property here called interestRate. It's a float and I'm giving it a literal value. But let's imagine that our business rules are such that interestRate should be the same for all BankAccounts. We might have a hundred thousand instances of this class, but they should all share the same interestRate.

Whatever it is, they all share it. Well I don't want a hundred thousand separate copies of this variable, and if it changes, to have to update it a hundred thousand times. So what I can do is define this as a type property so it works on the entire class. There's only one of them, and it will exist for the entire class whether I have a hundred thousand instances or even none at all. So I make it a class level or a type property by just adding the word class right in front of var. Now, as soon as I do this I'm going to run into one issue here.

At the time I'm recording this with a late beta version, I'm going to see this message that class variables are not yet supported. Now, to me, this suggests that it is expected to be able to do this. It's just not supported in my current beta. So if there is a need for you, just check to see if you can add the keyword class in front of a regular stored property because this may not be an issue at the time you're watching this course. However, I'm not stuck. I actually can do this right now as long as it's a computed property rather than a stored property.

So I'm going to make a quick change that instead of setting this equal to 2.0, I'll just add a code block here and tell it to return 2.0. So we have a read-only computed property here, and now that error goes away. Now when you have a type property working at the class level, the difference is that we don't use the name of an instance to deal with this. We use the name of the class itself, and we work with instance-level properties, normal properties here like accountNumber, routingCode and balance.

Well, I need to have an instance of that class to work with them. So down here at the bottom I'm creating two instances of the BankAccount class, firstAccount and secondAccount. And if I use those with dot syntax, I can get access to the accountNumber property, the balance property, the routingCode property. I do not see interestRate, because it doesn't work on an instance level anymore. What I need to do is use the name of the class, BankAccount. and now I get access to interestRate.

I can see in the playground just by writing this it's returning 2.0. And the thing is this, this type property is always available, even if we have no instances at all of this class. So if I comment out these two creations of the instances here, we don't have any instances of this class but this property is still available. Now we can also do the same thing with a method. We can convert a method from working at the instance level into working at the class level by writing the word class in front of it. Now, I wouldn't do this with methods like deposit and withdraw which are intended to work on instance level data.

But if I had another method, let's say I've got a function called example that just does a print line statement here. I could convert this into a type-level or class-level method by just writing the word class ahead of func. So this is now a type method, and like the type property before it we get to it by using the name of the class. So it's BankAccount.example, not any instance name of this. One important thing is because type methods where you've used the word class in front of them, they work on the class regardless of if you have any instances of this class or not so you cannot refer to instance-level data inside of this class.

Any attempt to access normal instance-level stored properties like the balance or the accountNumber would cause a compile error inside this method. Although, you can refer to class-level data like the interestRate property that we just made because that does work at the class level. So I could say interestRate is self.interestRate. That's completely accessible at this level because this is a class-level method. Now it is true that most of your properties and methods will be instance-level.

They'll work at that level, but these do come in very useful from time to time.

 

 


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


<== предыдущая страница | следующая страница ==>
Using inheritance Создание вычисляемых свойств| Using type properties and methods Используя свойства и методы типа

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