Swift Programming from Scratch
The Swift Sandbox is integrated, making the exercises interactive. Read more about the book here.
Chapter 3: Types
Introduction
All the values we’ve worked with so far have been integer numbers.
All variables and constants in Swift have a type. Think of the type as describing what kind of values a variable can have. The type for integer numbers is Int
.
You can see the type of a variable in Xcode by option clicking on it’s name (hold down option(⌥) and click on its name). A popup will appear were you can see the type of the variable.
Here you can see that our lucky number 7 is of type Int
.
We often need variables of types that aren’t Int
. You already encountered a different type. The expresssions inside an if statement. These values have type Bool
also known as Boolean
named after mathematician George Boole who layed out the mathematical foundations of Logic.
Comparision operators (<,<=,>,>=,==,!=
) produce values of type Bool
. Boolean expressions can have only one of 2 types true
or false
For example
var luckyNumber = 7
var condition = 777 > luckyNumber
condition
will be of type Bool
and have a value of true
as seen below:
The Double type
What if we want to use numbers of the form (1.5, 1.7, 1.6,...
)? We can of course do that in Swift! If you declare a variable lets say heightInMeters
with a value of 1.85
and check its type you’ll see that its type is Double
var heightInMeters = 1.85
Variables of type Double
hold fractional numbers and can be used for calculating fractional quantities. Any number of the form X.Y
is a Double
Examples: (35.67, 2.0, 0.5154, …)
Doubles can be added, subtracted, multiplied and divided using the familiar operators (+, -, *, /
).
There is no equivalent to the remainder(%
) operator for doubles.
var a = 3.5
var b = 1.25
print(a + b) // 4.75
print(a - b) // 2.25
print(a * b) // 4.375
print(a / b) // 2.8
Numbers of type double have a limited precision. consider the following code
print(1.0 / 3.0) // 0.333333333333333
Mathematically speaking the number ( 1.0 / 3.0
) should go on forever having an infinite number of 3s after the decimal .
. Computers can’t hold an infinite amount of information so they truncate the number at some point.
Representing decimal numbers in a computer is done via so called Floating Point Numbers. Represented by the typeFloat
in Swift. The Double
type is a kind of floating point number but compared to the Float
type it can hold twice as many digits hence the name Double
.
Declaring variables of a certain type
To explicitly declare a variable of a certain type you use the syntax:
var variable
: Type
= ...
For example:
var integer:Int = 64
var boolean:Bool = false
var double:Double = 7.2
If you don’t provide a type for a variable a type is automatically inferred for you using the value you provide
Examples:
// We don't declare a type for a it is implicitly Int
// because the value 7 is an Int
var a = 7
print(a / 2) // 3
// We don't declare a type for a it is implicitly Double
// because the value 7.0 is a Double
var a = 7.0
print(a / 2) // 3.5
If you explicilty declare a variable as having type Double
then you can initialize it with an integer but the variable will hold a Double
var a:Double = 7 // We explicitly declare a type for a
print(a / 2) // 3.5
Type Casting
Initializing a variable of type Double
with an integer only works if you use a constant value. If you try initializing a variable of type Double
with a variable of type Int
then you’ll get an error.
var a = 64
var b:Double = a // Error
To solve this problem we need to convert the value from Int
to Double
. Converting a value of some type to a different type is known as type casting
or just casting
.
To cast a variable to a certain type we use TypeName(variableName)
or the as
operator, variableName as TypeName
. For example:
var a = 64
var b:Double = Double(a) // b = 64.0
var c:Double = a as Double // c = 64.0
Casting a Double
to an Int
discards all the digits after the decimal point. Note that this digits can’t be recovered by casting the variable back to Double
.
Example:
var number = 5.25
var integerNumber = Int(number) // 5
var doubleNumber = Double(integerNumber) // 5.0
3.1 Average
You are given 2 Doubles a
and b
. Print their average.
Input:
var a = 2.0
var b = 5.0
Output:
3.5
Input:
var a = 20.0
var b = 40.0
Output:
30.0
Adding 2 numbers together and dividing by 2 gives you their average.
var a = 2.0
var b = 5.0
print((a + b) / 2)
3.2 Weighted Average
You are given 3 grades stored in 3 variables of type Double
finalsGrade
, midtermGrade
, projectGrade
. These grades are used to compute the grade for a class. finalsGrade
represents 50% of the grade. midtermGrade
represents 20% of the grade. projectGrade
represents 30% of the final grade.
Print the grade for the class.
Input:
var finalsGrade = 2.0
var midtermGrade = 5.0
var projectGrade = 3.0
Output:
2.7
Input:
var finalsGrade = 5.0
var midtermGrade = 5.0
var projectGrade = 5.0
Output:
5.0
x%
of a value
= value * x / 100
var finalsGrade = 2.0
var midtermGrade = 4.0
var projectGrade = 3.0
print(0.5 * finalsGrade + 0.2 * midtermGrade + 0.3 * projectGrade)
3.3 Tipping
You have the cost of a meal at a restaurant stored in a variable mealCost
of type Double
.
You would like to leave a tip of a certain percentage. The percentage is stored in a variable tip
of type Int
.
Print the total cost of the meal.
Input:
var mealCost:Double = 3.5
var tip:Int = 20
Output:
4.2
Input:
var mealCost:Double = 10.0
var tip:Int = 10
Output:
11.0
Don’t forget to convert tip
to Double
x%
of a value
is equal to value * x / 100
var mealCost:Double = 3.5
var tip:Int = 20
var tipCost = mealCost * Double(tip) / 100.0
var totalCost = mealCost + tipCost
print(totalCost)
3.4 Rounding
You are given a variable number
of type Double
. Create a new variable called roundedNumber
that has at most 1
digit after the decimal dot.
Input:
var number = 5.1517
Expected values:
roundedNumber = 5.1
Input:
var number = 32.5
Expected values:
roundedNumber = 32.5
Input:
var number = 2.0
Expected values:
roundedNumber = 2.0
Converting a Double
to an Int
discards all the digits after the decimal point.
var number = 5.1517
var intNumber = Int(number * 10.0)
var roundedNumber = Double(intNumber) / 10.0
3.5 Above average
You are given three grades obtained by 3 students in a class stored in variables grade1
, grade2
, grade3
of typeDouble
.
You are also given your grade in the class stored in a variable yourGrade
of type Double
.
Print above average
if your grade is greater than the class average or below average
” otherwise.
Note: the average of the class includes your grade.
Input:
var grade1 = 7.0
var grade2 = 9.0
var grade3 = 5.0
var yourGrade = 8.0
Output:
"above average"
Input:
var grade1 = 10.0
var grade2 = 9.0
var grade3 = 10.0
var yourGrade = 9.0
Output:
"below average"
Compare the average with your grade.
var grade1 = 7.0
var grade2 = 9.0
var grade3 = 5.0
var yourGrade = 8.0
var averageGrade = (grade1 + grade2 + grade3 + yourGrade) / 4.0
if yourGrade > averageGrade {
print("above average")
} else {
print("below average")
}
3.6 Fields
A farmer is harvesting wheat from a number of wheat fields, given in a variable numberOfFields
of type Int
.
Each field produces the same quantity of wheat given in a variable wheatYield
of type Double
.
Sometimes the harvest is increased by 50%
due to favorable weather conditions. You are given this information in a variable weatherWasGood
of type Bool
.
Print the total amount of wheat that the farmer will harvest.
Input:
var numberOfFields:Int = 5
var wheatYield:Double = 7.5
var weatherWasGood:Bool = true
Output:
56.25
Input:
var numberOfFields:Int = 5
var wheatYield:Double = 7.5
var weatherWasGood:Bool = false
Output:
37.5
var numberOfFields:Int = 5
var wheatYield:Double = 7.5
var weatherWasGood:Bool = true
var totalYield = Double(numberOfFields) * wheatYield
if (weatherWasGood == true) {
totalYield = totalYield * 1.5
}
print(totalYield)
Swift Programming from Scratch
Read more about the book here.
Feel free to ask any questions in the comments bellow.
Great tutorial! Much thankful for this. Thought I’d bring to your attention, for 3.3 Tipping, Example 1, my output was 4.375 instead of 4.2
Thanks!
The answer is 4.375 if you use 25% as tip. What Andrei has done however is that in his solution he used 20% tip instead of 25% tip as mentioned in the question hence the difference.
I am enjoying the exercises but it would be nice if each one had a different name for the variables so when copying over the initial problem I done have to rename variables things like “aa” rather than the default “a” that’s already been used in another question.
Also 3.6 your variable is named wheaterWasGood, I assume you mean weather and in that case you spelt it wrong in the variable.
This website is very useful for me as a beginner …… thanks thanks thanks……..
Glad to hear that!
Typo in 3.6.
Love the lessons!
Rounding off.
If I subtract 5.0 from 5.1517, I get 0.1516999999999
Is there a way to avoid the rounding off ?
The values are in double, I tried float but still the same issue.
Thanks
You can use NSDecimalNumber to avoid losing precision. Both double and float are floating point numbers so they will always have rounding issues. Only certain programs require a level of precision for which floating point isn’t precise enough, ex: Financial software. For most apps you can just round the number to the number of significant digits you need.
To round a number to 3 significant digits after the decimal point you can use “round(1000 * x) / 1000”
Under Type Casting, if I try using ‘as’ like in the example
var c:Double = a as Double // c = 64.0
The console output says executiong failed error: ‘Int’ is not convertible to ‘Double’
No problem is I use this
var b:Double = Double(a) // b = 64.0
Any ideas why? Thanks!
Maybe it worked in another version of Swift but not in this one – I could not test.
I think that you cannot do a type cast because the bits that form a Int dont form a Double with the same value. But you can use the value of an Int to create a Double with the same value.
I found an error:
in part “3.3 Tipping”, Example 1:
—————-
Input:
var mealCost:Double = 3.5
var tip:Int = 25
Output:
4.2
—————-
The correct answer is 4.375
Thanks, fixed.
Hi All,
In exercise 3.6
Shouldn’t it be “0.5” instead of “1.5”?
Since 50% is 0.5.
totalYield = totalYield * 1.5
Please note that the question says yield is “increased” by 50%, i.e. its original output + additional 50%, i.e. 100% + 50%, i.e. 1 + 0.5
I believe there is an error on exercise 3.2 Solution 1.
The output for:
var finalsGrade = 2.0
var midtermGrade = 5.0
var projectGrade = 3.0
Using the solution formula:
print(0.5 * finalsGrade + 0.2 * midtermGrade + 0.3 * projectGrade)
is 2.9, not 2.7
Can anyone verify?
it’s 2.9! The example has midtermGrade = 4 not 5 and that’s the 0.2 difference in the answers