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, andzand give them initial values - Declare another Int that is the sum of
x,y, andz - Declare two Doubles named
aandb - Declare a Double named
cthat isadivided byb - Declare an Int named
modthat is the remainder ofxdivided byy - Declare a Bool that is
trueisxis less thany - Declare a Bool that is
trueisxis less thanyandyis greater thanz - Declare a Bool that is
trueisxis less thanyoryis greater thanz - Declare a String set to "I have x cats" where x is
xand "cats" is properly pluralized (use+to concatenate strings and? :to checkx) - Declare an optional integer (
Int?) namedxNiland set it tonil. Then declare anIntnamedxOr5where you use the nil coalescing operator (??) to set it to eitherxNilor5. See what happens when you assign an actual integer toxNil. - Print the numbers from
1to5using a Range (...). - Print the numbers from
0to[1, 2, 3].countusing 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)