Chapter 3: Types

Swift Programming from Scratch

The book is updated for Swift 3 and the Swift Sandbox is integrated, making the exercises interactive. Read more about the book here.

  1. First Steps
  2. Conditionals
  3. Types
  4. Loops
  5. Strings
  6. Arrays
  7. Functions
  8. Recursion
  9. Closures
  10. Tuples & Enums
  11. Dictionaries

?You can buy Training app  +  the PDF and ePub versions of the book!

    cover final small     +     cover final small

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.

lucky

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:

luckier

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

Double

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
Why are fractional numbers called Double?(Optional)

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 .

[collapse]

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.

Example 1

Input:

var a = 2.0
var b = 5.0

Output:

3.5

[collapse]
Example 2

Input:

var a = 20.0
var b = 40.0

Output:

30.0

[collapse]
Hint

Adding 2 numbers together and dividing by 2 gives you their average.

[collapse]
Solution

var a = 2.0
var b = 5.0

print((a + b) / 2)

[collapse]

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. midtermGraderepresents 20% of the grade. projectGrade represents 30% of the final grade.
Print the grade for the class.

Example 1

Input:

var finalsGrade = 2.0
var midtermGrade = 5.0
var projectGrade = 3.0

Output:

2.7

[collapse]
Example 2

Input:

var finalsGrade = 5.0
var midtermGrade = 5.0
var projectGrade = 5.0

Output:

5.0

[collapse]
Hint

x% of a value = value * x / 100

[collapse]
Solution

var finalsGrade = 2.0
var midtermGrade = 4.0
var projectGrade = 3.0

print(0.5 * finalsGrade + 0.2 * midtermGrade  + 0.3 * projectGrade)

[collapse]

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.

Example 1

Input:

var mealCost:Double = 3.5
var tip:Int = 20

Output:

4.2

[collapse]
Example 2

Input:

var mealCost:Double = 10.0
var tip:Int = 10

Output:

11.0

[collapse]
Hint 1

Don’t forget to convert tip to Double

[collapse]
Hint 2

x% of a value is equal to value * x / 100

[collapse]
Solution

var mealCost:Double = 3.5
var tip:Int = 20

var tipCost = mealCost * Double(tip) / 100.0
var totalCost = mealCost + tipCost

print(totalCost)

[collapse]

3.4 Rounding

You are given a variable number of type Double. Create a new variable called roundedNumber that has at most 1digit after the decimal dot.

Example 1

Input:

var number = 5.1517

Expected values:

roundedNumber = 5.1

[collapse]
Example 2

Input:

var number = 32.5

Expected values:

roundedNumber = 32.5

[collapse]
Example 3

Input:

var number = 2.0

Expected values:

roundedNumber = 2.0

[collapse]
Hint

Converting a Double to an Int discards all the digits after the decimal point.

[collapse]
Solution

var number = 5.1517

var intNumber = Int(number * 10.0)

var roundedNumber = Double(intNumber) / 10.0

[collapse]

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.

Example 1

Input:

var grade1 = 7.0
var grade2 = 9.0
var grade3 = 5.0
var yourGrade = 8.0

Output:

"above average"

[collapse]
Example 2

Input:

var grade1 = 10.0
var grade2 = 9.0
var grade3 = 10.0
var yourGrade = 9.0

Output:

"below average"

[collapse]
Hint

Compare the average with your grade.

[collapse]
Solution

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")
}

[collapse]

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.

Example 1

Input:

var numberOfFields:Int = 5
var wheatYield:Double = 7.5
var weatherWasGood:Bool = true

Output:

56.25

[collapse]
Example 2

Input:

var numberOfFields:Int = 5
var wheatYield:Double = 7.5
var weatherWasGood:Bool = false

Output:

37.5

[collapse]
Solution

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)

[collapse]

 

Swift Programming from Scratch

Read more about the book here.

  1. First Steps
  2. Conditionals
  3. Types
  4. Loops
  5. Strings
  6. Arrays
  7. Functions
  8. Recursion
  9. Closures
  10. Tuples & Enums
  11. Dictionaries

?You can buy Training app  +  the PDF and ePub versions of the book!

    cover final small     +     cover final small

 

Feel free to ask any questions in the comments bellow. :)

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 5.00 out of 5)
Loading...

  18 comments for “Chapter 3: Types

  1. Gonzo
    February 13, 2015 at 1:37 am

    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 :)

    • February 13, 2015 at 9:32 am

      Thanks!

    • Srini K
      September 8, 2016 at 10:03 am

      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.

  2. February 18, 2015 at 10:56 pm

    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.

  3. Hajar
    March 2, 2015 at 2:56 am

    This website is very useful for me as a beginner …… thanks thanks thanks……..

  4. March 5, 2015 at 8:09 pm

    Typo in 3.6.
    Love the lessons!

  5. Anupam Sinha
    May 27, 2015 at 10:28 pm

    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

    • May 28, 2015 at 11:49 am

      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.

    • May 28, 2015 at 11:51 am

      To round a number to 3 significant digits after the decimal point you can use “round(1000 * x) / 1000”

  6. Karen
    June 25, 2015 at 3:33 am

    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!

    • June 25, 2015 at 9:04 am

      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.

  7. July 11, 2015 at 9:34 am

    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

  8. Chris
    July 14, 2015 at 10:35 pm

    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

    • Srini K
      September 9, 2016 at 9:36 am

      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

  9. July 29, 2016 at 6:41 am

    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?

    • October 3, 2016 at 10:46 am

      it’s 2.9! The example has midtermGrade = 4 not 5 and that’s the 0.2 difference in the answers

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe
We send about one email per week with our latest tutorials and updates
Never display this again :)