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

Defining and instantiating classes

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


Читайте также:
  1. Defining and instantiating classes Определение и создание экземпляра классы
  2. Defining and using enumerations
  3. Defining and using enumerations
  4. Defining functions
  5. Defining functions Определение функции
  6. Defining lazy properties

 

- Swift is an object-oriented language, so rather than write long procedural programs, we will split our code up into separate classes defining the data and the logic that belongs together. Now to define one it is the keyword class and then the name of your new class. As you are defining a new type, we'd begin it with an uppercase first letter. Now those of you that come from Objective-C will be very glad to know we do not need separate header and implementation sections anymore, it is all-in-one. Our entire class definition is contained inside these curly braces.

Now in a larger project we would normally put a new class in its own separate file, but for our purposes here I can just write this class definition in this playground. So we describe the data and behavior that this class will provided beginning with the properties and methods. Well it couldn't be easier, a basic Swift property is simply a variable or constant that's defined inside a class. There's no property keyword needed in Swift. We don't need to write getters or setters here. If you write a variable inside the class, it's a variable property.

You write a constant inside the class, it's a constant property. Now another comment for the Objective-C folks, the rest of you can ignore the next sentence. We do not have to worry about instance variables, and synthesizers and backing stores, it's all taken care of. It just works, hallelujah. All right, syntax here is identical to creating variables and constants outside a class, the same rules apply. If Swift can't infer a data type from some initial value we need to provide the data type. The type annotation here that name is a string and score is an Int.

If you do provide an initial value here, those will be used when an object of this class is instantiated. Now you might be noticing that there's an error popping up here. We'll talk about that in just a second. See for those of you who might be wondering, I want to confirm that yes these are regarded as instance-level properties, meaning if I instantiate 100 different objects from this one Player class, they would each have their own independent copy of name and score. And yes we can create class-level or what are called type-level properties, a piece of data shared across all instances, but hold your horses we'll get to that, basics first.

Well that's simply data, now to add some simple behavior we add methods. And like a property is just a variable or constant that's defined inside a class, a method is a function that belongs to a class. We use the same func keyword we've been using all along and all the same rules apply. In this case, I'm creating a method called description. It returns a string and it takes no parameters. But I am already getting a warning up here, I'll click this button, that class "Player" has no initializers.

It's not going to let me instantiate this class the way that it is. See Swift is, as ever, obsessed about all your values always having a valid state and right now there are no values for name and for score. So I had this potential that I could create an instance of this class and the values are in some indeterminate, indistinct state and that is simply not allowed in Swift. So I need to either provide some default values explicitly on these variables here or I need to provide what's called an initializer for this class, a special method to make sure that when it's instantiated it will immediately exist in a valid state and all the variables will have meaningful values.

Now I could also mark these variables here as optional, but that's not what I would want in this situation. So let's pick option one, just setting some default values to these variables. I can do it myself, just adding an equals sign and giving it some value, but if I notice that the error here has a couple of suggestions for fix it to fix name without an initial value. So if we pick name, I'll click that one, it's going to set it equal to an empty string, which is very unexciting, but it is technically an initial value.

And we still have the one for score, so I'll fix that one as well. Now I could change this to be some kind of more slightly meaningful value, so I'll change that to be a default value of John Doe. All right the error disappears, I can now instantiate this class. So outside of the class definition following the closing curly brace I'm going to define a new variable, which I'll call jake and I'm going to want this to be an instance of the Player class. What I do here is I just use the word Player, the name of our class name, and then opening and closing parentheses.

This will instantiate a new object of the Player class. In Swift we do not need a keyword like new, we don't need alloc, we don't need init, this is it. We now have a new object of the Player class. I can even see a clue over here that we have this object. I can QuickLook it, I can see there's two parts to it. There's John Doe is the name and the score is zero. Now I could use type annotation if I wanted to be explicit that my variable jake is type of Player, but like everything else in Swift if it's so obvious from this initial value that creates a Player object, I simply don't need that, the type is inferred.

And what I can now do is use dot syntax to access both the properties and the methods of this object. So jake.name = "Jake", jake.score = 1000, println jake.description and we start to see all the information that we would expect popping up over here in the result pane. So defining, instantiating and using a basic class in Swift is about as simple and straightforward as it gets in any object-orientated programming language. So let's take this a little further and begin with adding some initializers.

 

 


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


<== предыдущая страница | следующая страница ==>
Writing closures Написание закрытия| Defining and instantiating classes Определение и создание экземпляра классы

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