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

Creating computed properties

Creating optional variables Создание дополнительных переменных | Defining and using enumerations | 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 |


Читайте также:
  1. Blocks on the webpage (properties are written in CSS file)
  2. Classification of phraseological units according to their contextual properties is suggested by
  3. Creating a Bandpass Filter
  4. Creating a New Simulation
  5. Creating a Play List by Recording a Live Beat Arrangement
  6. Creating and using arrays
  7. Creating and using arrays Создание и использование массивов

 

- The kinds of properties we've seen so far just defining variables or constants inside a class do have a more specific name, these aren't just properties they are known formally in Swift as stored properties, that means that they're responsible for storing their own values, containing this data inside each instance of this class. Now that probably seems fairly typical and it is, stored properties are normal but there are other options. We can also create a computed property and that's a property that will calculate a value rather then internally store one.

So here's an example, I have a simple class called Person that contains two normal stored properties, firstName and lastName, both strings, I'm going to add a new computed property, fullName, a convenient way for someone to ask for the full name of the Person object. Now this is going to be typed as a string, but I don't want to duplicate this data, I don't want to store another copy of that information, I just want it to feel like it's an internal property, but actually calculate and return that data. Now right now this looks like a normal variable, but that's because we're not finished.

For a computed property, we then add a code block, just the opening and closing curly braces. And inside that we can add a code block for a getter, just the word get and another code block and this is where we will return the computed property, we'll calculate what it should be and send it back. We have to send back a string, because we have typed this as a string. Now optionally what you can also do is add another code block for a setter, to set the value it is very common that computed properties only have a getter and that would otherwise be known as a read only computer property, to do that I would just delete the set block.

And my getter for this example would be pretty simple, all I want to do is return a string that is firstName then a space and then lastName, I'm using concatenation here with the plus sign, though I could have also used string interpolation. Let's go ahead and prove that this works, down bellow I am instantiating a new object from the Person class, I am setting some basic data. So then I just want to go ahead and refer to that fullName property, so do a print line of examplePerson.fullName and we can see over here in the results pane that it's spitting out that as one string.

Now at the moment up here I do have a set block without any code in it, I'm just going to remove this to prove a point that with only a getter inside there if I do go ahead and try and set this value, so accessing it like it's a property, but just saying examplePerson.fullName = some new value I'm going to expect this to detect an issue here that we cannot assign to fullName, it is a read only computed property. Now if I really wanted to have a setter, so I'm gonna come back into the computer property block and add that set block back in again.

What I'd have to understand is what I'd be getting, I'd be getting a single string value passed in and I would need to write a little code to split this apart and put it in the firstName and lastName stored properties of this class because the computed property itself doesn't store any information. So when you add this set block, what you implicitly get inside is a new value called appropriately enough newValue. So I could add code here to split this newValue data into two separate pieces that would actually split it into an array and I could set firstName, the stored property to the first part of the array and LastName stored property to the second part of the array.

Now I'm not doing any error checking here so this is quite brittle code, this would be prone to breaking if somebody started to send in say three names inside this piece, or just one. But this would be the general approach, having said that most likely for this example we would make this a read only property and only have a getter, but at least you can see down here that it seems to be working, that we're not actually getting that error anymore because it's understood we do have a set block in our property. So this is what I'm going to do, I'm going to remove that entire set block and go back to the get.

This is going to make the error appear again, so I'll just go ahead and get rid of that, because in fact with computed properties it is so common to only have a get block that when that is the case, you can just omit it, you can get rid of the get block entirely and make it so the opening and closing curly braces of the get block is gone so the only thing that we have for our computed property is a return statement inside the main set of curly braces, now this is understood by Swift as a read only computed property and this is the simplest way to write one.

 

 


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


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

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