Unit 12: Instances, Methods, and Properties Flashcards
Initialiser
sets up an instance so that’s ready to be used; after declaring a name for a constant or variable, you initialise the constant or variable by assigning its first value (e.g., Date () / Circle (radius: 44.0))
Literal
e.g., “hello”
Instance
a value of a particular type (e.g., let greeting = “Hello” (instance of a String); types are capitalised (String), but instances are lower case (greeting)
Method
a function defined inside a type; methods can use the data stored in the type’s properties to do work
Property
a piece of data held by a struct, class or enum (e.g., each Array instance has a count property that is different depending on the characteristic of the particular array)
For Instance
You’ve learned about types in Swift and how they’re similar to types of things in the real world.
For every type in the real world, there are many actual physical instances:
For the type “Car” there are countless individual variations on the road, each with its own mileage history, make, model, color, fuel level, scratches, and dents. Each car also has a particular set of behaviors: its own methods for starting, braking, shifting, and the like.
For the type “City,” each instance of a city has a different name, population, location, and landmarks. And a city has certain methods for getting things done like responding to emergencies or collecting garbage.
The type defines or describes the properties and behaviors of a particular kind of thing. But each concrete example of the type — each car, each city — is a separate, independent instance of the type.
Imagine two cars of the same make and model, built in the same year. One is speeding down the highway on a trip; the other is out of gas by the side of the road. Same type, but two different instances.
Or think of two cities. The location of each city will be different. A landmark in one city might draw lots of tourists, but a landmark in another might be in disrepair and get few visitors. Both are cities, but each individual city can be very different from the next.
In programming, you can create and use different instances of a given type. Each instance has its own set of property values, and each instance can perform behavior independent of other instances.
Next, see some instances in code.
Instances
You’ve already worked with a variety of types in Swift, such as String. An individual String value, like “hello”, is called an instance of that type.
String is a type
“hello” is an instance of a String.
You’ve been creating instances of type Int and String for a while now. In fact, each value you make in a program is an instance of its type.
The constants hello and aDifferentHello are two String instances that happen to hold the same data.
let hello = "hello" let aDifferentHello = "hello"
You’ve seen that the type of an instance determines what kind of data it contains and how you can use it in code.
You’ve also performed a few operations on instances: adding strings together and doing calculations on numbers. But instances can be a lot more powerful than that.
In this playground, you’ll learn more about creating and using instances, including accessing their values and behaviors.
Next, learn some new ways to create instances.
Creating an Instance
So far, you’ve created almost every instance by typing a literal value directly into code. The exception was in the Types playground, where you used Date() to create a value holding the current time:
import Foundation
let literalString = "Howdy!" let literalBool = false let literalInt = 84
let rightNow = Date() /*: `Date()` looks a lot like a function, but with an important difference: It uses a type name instead of a name beginning with a lowercase letter.
This is an example of an initializer. You use an initializer to create a new instance of a particular type. Only a few types, like String
, Bool
, and Int
, can be created using literals, but every type has at least one initializer.
Even types you’ve been creating using literals have initializers: */ let emptyString = String() let falseBool = Bool() let zero = Int() //: You’ll often want to provide more information when you create an instance. Many types have initializers with parameters to let you do this: let oneHourLater = Date(timeIntervalSinceNow: 3600) /*: This initializer gives you a `Date` that is a number of seconds from the current time.
Initializers and functions are similar in some ways:
- They can have parameters or no parameters at all.
- You call them the same way, by passing in required argument values.
But they also have differences:
- You use the name of the type when calling an initializer
- An initializer returns a new instance of its type
Next, learn about the extra abilities some types have.
Methods
Functions can be defined as part of a type. These functions are called instance methods, or just methods. String has many instance methods, which are used for common operations.
Here are two string instances:
let introduction = "It was a dark and stormy night" let alternateIntroduction = "Once upon a time" /*: It’s often useful to know if a string begins with another string. The method `hasPrefix()` can answer this question.
The method is declared like this:\
func hasPrefix(_ prefix: String) -> Bool
The method hasPrefix()
has a String
parameter, which is the prefix you want to test, and returns a Bool
.
Instance methods are called by using a period (.
) after the instance, followed by the method call:
- /
introduction. hasPrefix(“It was”)
introduction.hasPrefix(“It wasn’t”)
alternateIntroduction.hasPrefix(“It was”)
alternateIntroduction.hasPrefix(“It wasn’t”)
/*: This is known as calling a method _on_ the instance. You’ve called `hasPrefix()` on `introduction`.
In the results sidebar, you can see that the method hasPrefix()
returns different answers depending on the value of each argument and the value of the instance. You can call this method on any instance of String
and you will get the correct answer, because every string instance knows how to figure out the answer for itself. Every instance of String
has this built-in functionality ready to be used.
> You don’t need to pass in the value of introduction
. The method is being performed by the instance assigned to introduction
, so the value is already available to it. You’ll learn more about this in later lessons.
Next, find out how Swift helps you use instance methods safely.
Methods and Type Safety
Type safety still applies when you’re using instance methods. hasPrefix is a String instance method, so you can’t use it without an instance.
Uncomment the line below to see the error. Re-comment when you’re done.
The error you see is “Use of unresolved identifier ‘hasPrefix’.” This means Swift can’t find a function named hasPrefix that can be called on its own.
//hasPrefix("It was") /*: You also can’t use an instance method on an instance of the wrong type. You can only use methods that are part of, or _members_ of, a particular type.
- Experiment: Uncomment the line below to see the error. Re-comment when you’re done.\ The error this time is “Value of type 'Int' has no member 'hasPrefix'.” This means there isn't a `hasPrefix` instance method on the `Int` type. */ let number = 42 //number.hasPrefix("It was") /*: Next, learn about values that types can hold.
Properties
At the start of this playground, you thought about different types like “City” and “Car.” You can imagine each instance of a city having a different name or each instance of a car having its own mileage.
Similarly, in Swift, each instance has one or more pieces of associated information. These values are known as properties.
It’s often useful to know if a string contains any characters at all. The property isEmpty answers this question.
The property is declared like this:
var isEmpty: Bool { get }
The declaration looks similar to a variable declaration. Just as a method is a function built in to each instance of a type, a property is a constant or variable built in to each instance of a type.
The property is named isEmpty and is of type Bool. It is marked var because the property value could change if the string contents change.
The { get } indicates you can only get the value of this property, but you can’t set it. This is also called a read-only property.
Properties are called by using a period (.) after the instance, followed by the property name:
let something = "It was the best of times" something.isEmpty
let nothing = “”
nothing.isEmpty
/*:
The same type safety rules apply for properties as with methods:
- You can’t use a property without an instance.
- You can only use properties that are part of the type of the instance.
> The types you’ve worked with so far don’t have many properties, because the information they store is very simple. You’ll learn about more complicated types in a later lesson.
Properties Versus Methods
What’s the difference between a method and a property? When would you use each one?
Variable versus Function
The difference between a method and a property is similar to the difference between a function and a variable or constant.
A variable is useful for referring to a value that you can access when required. Similarly, a property provides a way to get or set a value that’s part of an instance. Each instance can have a different value for that property.
A function is useful for providing behavior that can be repeated as needed. A method works in the same way, providing behavior specific to that instance.
Arguments
If the work you want to perform needs extra information, then it must be a method, since you can’t pass arguments to a property.
That means hasPrefix() must be a method, because you need to pass in the prefix you’re testing for.
Side Effects
If the work has side effects, things that happen that aren’t related to the return value, then it’s a method. For example, String has a method, removeAll(), which empties the string:
var magic = "Now you see it" magic.removeAll() magic /*: ### Values
Properties are for getting values from an instance and, as you will see later, for setting values on an instance. Properties don’t do any additional work.
### Both Are Used Often
When you’re building an app, almost all of code you write is in the form of instance methods or properties on types. And they’re often on types that you create. An app is made of many instances of different types, all working together.
In the following pages you’ll learn about some ways of discovering and understanding the methods and properties available to you.