This article is part of a series on learning Swift by writing code to The Swift Programming Language book from Apple.
Read each article after you have read the corresponding chapter in the book. This article is a companion to Basic Operators.
Set up a reading environment
If you are jumping around these articles, make sure you read the Introduction to see my recommendation for setting up a reading environment.
Exercises for Basic Operators
At this point, you should have read Basic Operators in The Swift Programming Language. You should have a Playground page for this chapter with code in it that you generated while reading the book.
In your Playground write code to do the following
- Declare three Ints named
x
,y
, andz
and give them initial values - Declare another Int that is the sum of
x
,y
, andz
- Declare two Doubles named
a
andb
- Declare a Double named
c
that isa
divided byb
- Declare an Int named
mod
that is the remainder ofx
divided byy
- Declare a Bool that is
true
isx
is less thany
- Declare a Bool that is
true
isx
is less thany
andy
is greater thanz
- Declare a Bool that is
true
isx
is less thany
ory
is greater thanz
- Declare a String set to "I have x cats" where x is
x
and "cats" is properly pluralized (use+
to concatenate strings and? :
to checkx
) - Declare an optional integer (
Int?
) namedxNil
and set it tonil
. Then declare anInt
namedxOr5
where you use the nil coalescing operator (??
) to set it to eitherxNil
or5
. See what happens when you assign an actual integer toxNil
. - Print the numbers from
1
to5
using a Range (...
). - Print the numbers from
0
to[1, 2, 3].count
using a Range (..<
). - Print the values of
[1, 2, 3, 4, 5]
starting from the 2nd value (2
) using a one-sided range.
Next: Strings and Characters
The next article will provide exercises for the Strings and Characters chapter.
Top comments (0)