Unit 9: Types Flashcards
Framework
a group of types and capabilities
e.g., HealthKit/ MapKit/ Social
Integer
a whole number with neither fractions nor decimals
Type
a named grouping of properties (features) and methods (behaviours) of a kind of data
type case is always capitalised in Swift (e.g., Double, Swift, BicycleRoute)
Type annotation
used when Swift needs more information about the type of an instance or argument (e.g., UIColor -> CGFloat instead of the default Double; correct type annotation (let redComponent: CGFloat = .76))
Type Inference
used to ascertain a certain type from the available information, even when the name of the type isn’t explicitly put into words in code (e.g., func answer () -> String ; constant: let nextIdea = answer () {used to find the answer to the result})
Important Types
In real life, using the right kind of object is very important.
If you’re playing tennis, it’s important to use a ball instead of some other kind of thing, like an egg. On the other hand, having a dozen tennis balls is not very useful if you are trying to make an omelet. Different types of things have different properties and behaviors. A tennis ball is filled with air and bounces if you drop it. An egg is filled with egg white and egg yolk and breaks if you drop it. In programming, types work in much the same way. For example, you’ve already used a type called a string to work with characters and text. Strings have properties and behaviors that are tailored for that purpose. Move on to learn more about types in Swift.
Types
In Swift, every value has a type.
Just like types of things in everyday life, each type in Swift has its own set of properties and behaviors. You’ve already worked with two different types of values: Strings like "Hello" and "Wimbledon" Numbers like 101 and -10 let string = "I am a string" let number = 12 //: You’ve also seen that these types behave differently. What happens when, for example, you add them together? 1 + 1 // Equals 2 "1" + "1" // Equals "11" /*: The name of the string type in Swift is, conveniently enough, `String`. The name of the number type you’ve been using is `Int`, an abbreviation of integer. An `Int` value is a whole number with no fractional component. An `Int` can be a positive number, a negative number, or zero. So far, you’ve only been introduced to two types, but there are many more to come. Learning how to use different types and even creating new types of your own will be a big part of learning to program. Imagine a toolbox with a socket wrench, a screwdriver, pliers, and a hammer. Each type of tool is good for certain tasks — and not at all useful for others. Every time you learn how to use a new type in Swift, you’re adding a new tool to your programming toolbox. Take a moment to picture your favorite shirt, then move on to the next page.
Favorite Shirt
If you take a moment to imagine your favorite shirt, it’s probably not a banana. That doesn’t make sense. A banana is not a shirt.
On the other hand, if you think about your favorite fruit, whether it’s a banana, an apple, or something else, it’s almost certainly some kind of fruit. When people name something — “favorite fruit” for example — the name is usually connected to a particular type of thing. The idea of “favorite fruit” only makes sense if it’s connected to a kind of fruit. It just wouldn’t make sense to connect it with “monkey wrench” or “astronomy.” Your brain does a good job of making sure names are matched up with the correct type of thing. In a similar way, Swift keeps track of the type of value associated with constants and variables — and makes sure you don’t accidentally make a value a banana when it’s supposed to be a shirt. Next, find out about types and variables.
Types and Variables
The first time you assign a value to a variable, the variable’s type automatically becomes the type of the value.
From then on, Swift keeps track of the type of the variable and makes sure you don’t accidentally try to assign a value of a different type. Uncomment the line below to try to set favoriteThing to the value 42:
var favoriteThing = "Whiskers on kittens" //favoriteThing = 42 /*: You’ll see an error that says `Cannot assign value of type 'Int' to type 'String'`. This is important: The _value_ of a variable can change, but the _type_ of the variable can’t change.
This rule helps you to avoid mistakes and confusion in your code. - callout(Exercise): Update the line above with the error so that the variable can be updated. How do you write a `String` instead of an `Int`? Next, learn other ways Swift protects you when working with types.
Type Safety
You saw that trying to assign the wrong type of value to a variable caused an error. In fact, Swift won’t let you write code that uses types incorrectly or unexpectedly. This is called type safety — and prevents you from making all sorts of errors in your code.
Another instance of type safety would occur if you tried to add values of different types. Uncomment each line of code below and examine the error it produces. You’ll need to uncomment one line at a time, because the playground will stop at the first error it sees.
//"banana" + 1 //2 + "2" /*: You'll see errors like this:
`Binary operator '+' cannot be applied to operands of type 'String' and 'Int'`. This slightly scary sentence is saying something quite simple: - `Binary operator '+'`: The `+` addition operator (which you learned about earlier) is called a _binary operator_. A binary operator expects something to the left of it and something to the right of it. - `cannot be applied to operands`: _Operands_ are the things the operator works with, such as the “banana” string or the integer 2. - `of type 'String' and 'Int'`: The things to the left and right of the `+` are a `String` and an `Int`. The `+` doesn’t know how to add those things. Do _you_? - callout(Exercise): Write some more incorrect addition statements. Before you write each line, try to guess what errors will be produced. Remember to comment out the lines of code from the earlier experiment first. * /
Types & Literals
When you write a value in code — like 42 or “hello” — it’s known as a literal. Swift makes assumptions about what types the literals are meant to be.
For example, any value inside double quotes will be treated as a String and a whole number will be treated as an Int. If you invite some friends to the beach and they meet you wearing swimsuits, you’d use that context clue to infer that they’ll jump into the water with you. When Swift uses context clues from code to infer what type something is, it’s called type inference. There’s another common type that can be inferred. You already know that whole numbers are inferred to be Int types, but if you type a number with a decimal point, it will be inferred to be a Double type.
let partNumber = 3.2 let wholeNumber = 2 /*: You can always find out which type Swift inferred by holding down Option and clicking on the identifier:
![Quick Help window revealing the inferred Int type of wholeNumber](quick_help.png) */ //: - experiment: Try to perform a calculation with `partNumber` and `wholeNumber`, for example add them together. Look at the errors. Change the values to be both whole numbers, or both decimal numbers, and see what difference it makes.\ //:\ //: You can‘t mix and match `Double` and `Int` types in Swift because of type safety.
/*: > The `Double` type is so called because it refers to a “Double-precision floating point” number. A `Float` type also refers to a number with a decimal point, but the default `Double` is twice as precise.\ > \ > Below is an example of precision in floating point numbers. Why would you ever want to use less precise decimal numbers? One reason: if you have a huge amount of data, the `Float` type will save space because it occupies half as much memory. If your calculations only require accuracy to the nearest hundredth, then there's no reason to store all those extra digits. Swift's default is `Double` because typical programs don't work with enough numeric data to cause issues with memory, and more accuracy makes your code less prone to subtle errors.\ > \ > (On page 8 you'll explore the syntax of `let doublePi: Double`.) */ let doublePi: Double = 3.141592653589793238462643383279 let floatPi: Float = 3.141592653589793238462643383279
doublePi floatPi //: Next, find out another way Swift decides on types.\ //:\
Type Inference from Assignment
When you write a value in code — like 42 or “hello” — it’s known as a literal. Swift makes assumptions about what types the literals are meant to be.
For example, any value inside double quotes will be treated as a String and a whole number will be treated as an Int. If you invite some friends to the beach and they meet you wearing swimsuits, you’d use that context clue to infer that they’ll jump into the water with you. When Swift uses context clues from code to infer what type something is, it’s called type inference. There’s another common type that can be inferred. You already know that whole numbers are inferred to be Int types, but if you type a number with a decimal point, it will be inferred to be a Double type.
let partNumber = 3.2 let wholeNumber = 2 /*: You can always find out which type Swift inferred by holding down Option and clicking on the identifier:
![Quick Help window revealing the inferred Int type of wholeNumber](quick_help.png) */ //: - experiment: Try to perform a calculation with `partNumber` and `wholeNumber`, for example add them together. Look at the errors. Change the values to be both whole numbers, or both decimal numbers, and see what difference it makes.\ //:\ //: You can‘t mix and match `Double` and `Int` types in Swift because of type safety.
/*: > The `Double` type is so called because it refers to a “Double-precision floating point” number. A `Float` type also refers to a number with a decimal point, but the default `Double` is twice as precise.\ > \ > Below is an example of precision in floating point numbers. Why would you ever want to use less precise decimal numbers? One reason: if you have a huge amount of data, the `Float` type will save space because it occupies half as much memory. If your calculations only require accuracy to the nearest hundredth, then there's no reason to store all those extra digits. Swift's default is `Double` because typical programs don't work with enough numeric data to cause issues with memory, and more accuracy makes your code less prone to subtle errors.\ > \ > (On page 8 you'll explore the syntax of `let doublePi: Double`.) */ let doublePi: Double = 3.141592653589793238462643383279 let floatPi: Float = 3.141592653589793238462643383279
doublePi floatPi //: Next, find out another way Swift decides on types.\ //:\
Type Annotation
If Swift can’t work out the type of something, it will let you know.
Uncomment the line of code below and look at the error. Comment out again when you’re done.
// let mysteryConstant /*: The error `Type annotation missing in pattern` means that Swift is unable to infer — work out from the available information — the type of the constant.
There may also be times when you don’t want Swift to use type inference, because it might not give you the type you want, as in the calculation with `Double` and `Int` types you attempted earlier.
In these cases, you can add an extra piece of information, called a _type annotation_, to tell Swift exactly what type you want to use. Type annotation is entered right after the name declaration, using a colon and the name of the type: */ let annotatedDouble: Double = 20 let inferredDouble = 0.5 let result = inferredDouble * annotatedDouble result * 0.5 /*: - `annotatedDouble` is a `Double`, even though there is no decimal point, because of the type annotation. - `inferredDouble` is a `Double` because it is written with a decimal point. - `result` is a `Double`, because the result of `Double * Double` is a `Double`.
Next learn where the types you’ve been using so far come from.
Where Do Types Come From?
Swift has built-in types that represent the basic building blocks of all programs. You have spent a lot of time with String and Int, there are also many more.
They’re part of the Swift standard library. All programming languages have something similar — the basic set of capabilities required to do fundamental programming tasks. You’ve spent a lot of time with String and Int types, but there are also many more. Here are a few of the other types from the Swift standard library. Don't worry about what any of them mean right now, though feel free to take a guess:
Array Dictionary Set Sequence Error Bool
Notice that all the type names begin with a capital letter and — if there are multiple words — the first letter of each word is also capitalized. This is slightly different from the rules for naming constants, variables, and functions, which all begin with lower-case letters. The difference is intentional. Because names of types begin with a capital letter, it’s easy to tell them apart from the names of functions, variables and constants. Both use camel case, but types use upper camel case as opposed to lower camel case. Think of some types of your own and how they'd look in upper camel case, like TrainingShoe or RacingBike. There are more types available. Find out where they come from on the next page.
Beyond the Standard Library
Programmers can also create their own types by combining and adding to the types and capabilities in the standard library. You’ll create your own as you progress through this course.
Take one of your made-up types from the experiment on the previous page, and imagine what types it might depend on. For example, a TrainingShoe might use an Int for a size, a String for a brand name, a Date for its release date, and another Int for its price in dollars. Types and capabilities can be grouped together into collections called frameworks or libraries. When making apps, you can draw from frameworks included within Xcode. One very important framework is the Foundation framework. The Foundation framework introduces lots of types used to represent more specific things than just strings or numbers from the Swift standard library. For example, there are types for dates, distances, and files on a computer. These extra frameworks aren't added automatically to your programs, because you might not need them. It would be like taking everything you own on a quick trip to the mall. You’ll learn how to add frameworks to your programs on the next page.