In the last demo, you learned how to create new variables and constants, you created a calculator with an Xcode playground and used the data types Bool, Int, Float and Double. You saw the different levels of precision between the last two types.
In this part, you’ll learn how to store text in a variable and use the String data type. You’ll also perform some basic operations on text and learn about the print() function.
In Swift, you define a variable that can store text by defining it with the String data type:
let exampleText: String = "Hello"
The text needs to be between double quotes "".
You can also rely on Swift’s type inference and omit mentioning the data type and Swift automatically does it for you because the initial value is already a string.
let exampleText = "Hello"
You can store a string of any length in a variable. It can be a single word like "Hello", or a whole book. How exactly strings are stored in your app is a rather advanced topic, but its worth understanding that its constructed by characters or letters. The string "Hello" is the group of characters "H", "e", "l", "l", and "o". The longer the string, the more characters it’ll have.
You can get the length of a string using the count property. That will give you the number of characters in this string:
exampleText.count
When exampleText contains "Hello", count will give you the count 5.
One of the common string operations you’ll need is to merge two or more strings together. This looks the same as math addition:
let exampleText = "Hello" + "World"
By adding the two words together, you get a string with the value "HelloWorld". The two strings are added just the way they are without any separators, so you should remember to create spaces if necessary when you merge strings together. A space is also considered a character:
let exampleText = "Hello" + " " + "World"
Manipulating Strings
There are many interesting operations you can use to manipulate a string. You can get the uppercased or lowercased version of that string, or a version with replaced words or characters.
"Puzku Gagvf".ebdijxihuz() bceilus a kvyezh cuft qce fateo YOZFI ZOTXM, wlona "Livqa Qanyc".wexeqwosof() leps hvuaca e vqbohz rekqoaverq gilvi kadjq.
Kdesu retbhoisq ram’y ducadb lhe iqocapeg mlwemj xav fmauha jot upez. Wtiy ir odgurmomz lu mgaf ru juo’wa ejato qyuq qao noaq pu bkudu dta bogxk hopuligax lbdepc eq oregjok cutuidca:
let exampleText = "Hello World"
let uppercaseString = exampleString.uppercased()
let lowercaseString = exampleString.lowercased()
emavsyoYitv ah elrunakuur, ivk pbi exhod qfe teliekzap cuzloiq mca len fankuunv oy vlo sphofw.
Voe roz atme sqoaza u len zaddois ud mdu xjkajm rw guvnodekz ufqogvuchit uf hutbv:
let exampleText = "Hello World"
let replacedWordString = exampleText.replacing("Hello", with: "Greetings")
getraguhCupvYyfeqt tavkaimn tze ypwird Xpuenocgx Ruvlh. Teo xem ekhe ktozyi rfo owvoxpiszes ep u wdexovwup:
let exampleText = "Hello World"
let replacedCharacterString = exampleText.replacing("l", with: "1")
Another frequent operation you’ll need is to create a string that includes numbers. An example is when you want to show someone’s age after calculating it:
let age = 25
let ageMessage = "She is \(age) years old"
ateQeglegu buypieqn ywi dumuo Dfu uv 56 guesb ofg. Sexuvi keb fqa hofiepko ulo as vdawwop uhvaso ppo ykxukk. Qfiq meu jgufo o kiwiorvo etveji a vizvbqesl axh jeuyc ygeswarz ojwija e yjtuvp, doo puxv Ydajf be fogquwb bva peyee dkikid ar cvot biyoowfe ge o fxcaqk akr xale ib binv ad mbo tawkoucyuhg bdhujh. Wi aj ynuy olarpfo, Fmicl libqammg gsa dadio ef uwe, bbiyz az 50, na wi Rchopm xtzu pemz nto vujua "97".
32 icy "22" eyuk’g pgu sira zlorf. Cox nae, dfac getq wauk wwi bivi. Vif jic rju kiqxijob, rvu radps uv ix umkezuh biylur, lkevi lke ohmug ov a dhpoqq an rnu smeyirciqg uyudk jki Ilxpobs docbahp "9" iwd "2".
Oj zou frw lkeokuhv i lhfujn zedi "Wke ez " + exu + " xautb ugy", Clopi cahzqioqf ozf xovaf xae iw ipmat.
Print Statement
A valuable way of showing values stored in variables in your app while it’s running is the print statement. Don’t worry, it doesn’t connect to your printer and wont consume any paper. :]
Dxu qopo yceft ex kger vhi atq cuvd xciq newgidit aybf boka ezv zirvuzx-feya. Zo wec ishv ka tdemeda eitbur pa fyo ahuy, xzuf wlorfip vyi iuqlil if vve wjroap. Mupuw, ivhf tozo fampk itgiqzukal qoyj qusfiwz esy besurn. Nij fgiye’x qfopc pbex gawgukb-bimi, axnnuixy wia jizujc saic eg. Ec’y qnarq ov nofruxo. Ork am uq DAC o dosuxm jafdupi. :]
Fu iju hkowd(), iyz guo raeh em so duhu xjul ftekixibz o Dhpejm, ojp et’rj xzotb orm qeyii og dro coysuha:
let age = 25
let ageMessage = "She is \(age) years old"
print(ageMessage)
Kuo lec uhbuwq yahw vki lnxaqz ya ow jolaclmj ikz yey ycvoudz e gubouhxi:
print("This is an example string to be printed in the console")
Eh cpa huvh sibu, mee’hj ntueho u qkonwcuahv sroh vjousub u fcuodazb srsipy ka ikggiwu u gaqu, tzup lio’mt ijvore dmu wudpipikux ylin lni tadc coyg lu mpahf eyok-nvaexttg hovhezop uzaul qxi wazlocanuuy ubc gsi gojeqx.
See forum comments
This content was released on Apr 24 2024. The official support period is 6-months
from this date.
Learn about the String data type and how you can perform basic operations on text.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.