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 Strings and Characters.
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.
Generate exercises from a app idea
In the second article in this series, I recommended:
if you have an app idea, keep that in mind. If you don't, just pick some app you use and know well and keep that in mind. [...] I will show you how I use that to generate exercises for myself.
Sometimes when you want to practice a programming language you don't know yet, it can be daunting to figure out what to do. Like practicing scales to learn piano, it's beneficial to practice one new thing at a time in isolation.
So, for the examples I am going to provide, I will only use knowledge that we have gotten from the chapters we have already read.
Exercises for Strings and Characters
At this point, you should have read Strings and Characters 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.
To generate examples, I am going to us the app idea of Flash Cards that help you study a foreign language. Use google translate to find out how to say things in other languages.
In your Playground write code to do the following
Declare five strings called
hello1
,hello2
, etc and set them to strings that are "Hello, World" in other languages. Include languages that don't use the latin alphabet (like Japanese) and languages that display right-to-left (like Arabic or Hebrew).Concatenate the Strings (using
+
) with a space separating each one.Create a multiline string (using
"""
) with a verse from "It's a Small World" in another language.Use flag emojis in your strings from Exercise 1.
Enumerate the characters in a string using
for c in "string"
Create the same string as you did in exercise 2, but use interpolation: (e.g.
"\(s)"
)Create a string with interpolation that has the lengths of each
hello
string rather than the string itself.Use substrings to get just the "Hello" part out of each string (skip the ones you don't understand). So, for example, for Spanish, you could use "Hola Mundo" -- so for this exercise, get the substring containing "Hola" into another variable.
Concatenate the variables you created in step 8.
Declare a boolean that is set to the result of comparing your hello strings with
<
Go back and read the section of the chapter called Unicode Representations of Strings. Practice your understanding with your example strings.
Next:
The next article will provide exercises for the Collection Types chapter.
Top comments (0)