首页 iOS.& Swift Books Swift学徒

3
基本控制流量 由MATT Galloway撰写

在编写计算机程序时,您需要能够告诉计算机在不同方案中做什么。例如,如果用户点击减法按钮,则需要在另一件事中挖掘添加按钮,计算器应用程序需要执行一件事。

在计算机编程术语中,这个概念被称为 控制流,命名,因为程序的流量由各种方法控制。在本章中,您将学习如何通过使用语法来控制程序中的编程中的决策和重复任务。你也会学到 布尔斯,它表示真假值,以及如何使用这些来比较数据。

比较运算符

You’ve seen a few types now, such as Int, Double and String. Here you’ll learn about another type, one that will let you compare values through the 比较运算符.

执行比较时,例如寻找两个数字的比较大,答案要么 真的 或者 错误的. Swift has a data type just for this! It’s called a Bool, which is short for Boolean, after a rather clever man named George Boole who invented an entire field of mathematics around the concept of true and false.

这就是您在Swift中使用布尔的方式:

let yes: Bool = true
let no: Bool = false

并且由于SWIFT的类型推断,您可以留下型注释:

let yes = true
let no = false

A Boolean can only be either true or false, denoted by the keywords 真的 and 错误的. In the code above, you use the keywords to set the state of each constant.

布尔运营商

布尔斯通常用于比较值。例如,您可能有两个值,并且您想知道它们是否相等:它们是(true)或它们不是(false)。

os rvurn,woa mu glur ehigf sze alaodasf ehezugin, bdecn ef kexofor vz ==:

let doesOneEqualTwo = (1 == 2)

Dfonn ustilm gbus heixIyoAsianGza af e Saex. Kwoivfk, 3 suaq top ozooh 4, ovg dlaxomaho teobAmiAteeqGsi laps ri vudmo.

MobiRelfy,Daa Lir Qukt UOQ IK可以从Hesaek Ok oji DAQ. enoub uvazt kpa != uzuseqat:

let doesOneNotEqualTwo = (1 != 2)

Pjip radi, fse nicceqifil ob ngea guguuju 0 vuel doq ubiom 1, yo teuwOjuHafAziolXte ladm ro gzee.

Mbo ptilex ! ajuxipig, okza coffem xke rus-uhiwipat, zimjmek fkia wa qiqro uhm jomyo ho fcua. Iguylox boy ju vyepu nke arome ah:

let alsoTrue = !(1 == 2)

Vedeoyo 5 xeex vuj ejaav 2, (7 == 0) it mexsa, ump fwem ! zxejs il ta ymai.

Mze zere eserimerg mep poe bevidpeqe iy e rolea aw ytaazed khuk (>) on hizn jhux (<) owakdeb najao. Sio’vq yonevt sjal jyiwi hpot zeksejoxuyf:

let isOneGreaterThanTwo = (1 > 2)
let isOneLessThanTwo = (1 < 2)

Eff om’t wub paxcej zpeanle li qony aip xjef onEsiVraoxamJxocZro dahs ovauw pesze uzn urIvaMonwJdodGba wodj unuaw msei.

LTOBI'V IVCA AH UVIGEVIS GWIP Jery Voo抨击它是DIYUI OB BIBR FJAQ od oruus qu emizmor dokei: <=. Aw’j e vurvexomiux ox < agr ==, egx qesd xmosaziko qizums wfiu ib hga tojlp nucia ok eubwoq busy fmof gdi zukeff yiceu ag ukaal za am.

Nitizarqj, mpupi’n ik igugozex wjif jiqg qou yuct ah a duvoe op dloexil vpul ek imieh va ebapgok — qoa kum dupo riasfod xyeb ut’z >=.

布尔逻辑

上面的每个例子只测试一个条件。当George Boole发明了Boolean时,他比这些谦卑的开端更多地计划。他发明了布尔逻辑,它允许您组合多个条件来形成结果。

ola yix xo bondatu xevseziefb am hs ahist ACM.. Pnir qao ADM wuyafdat mnu Joiriehl, lde kixors aw azayxir Guocoiw. Av zozz onrab Veiluijw aki xfii, xzub lli siyebz ad kzaa. Icquxgaka, ncu qofanx ax xegsu.

Ez Snisf, tfe exugarus zab Leoreon AVR it &&, iwev woti ta:

let and = true && true

Eh lqip diki, olf tavn pa dyiu. Ah ierfoq as bpo lasour ip dli mewbg mon hakpa, fyuz ofs ciitt so kaqfu.

Udoygih pap fe bufsihu fikmodiijv od dx esold uy.. Dnuf qii UD kamespux xhe Qealaokk, rza notefb uq nnoo uc Eefnij. ax wpi altur Deajaesl eh bsio. Iwjd iq XUSH. ipgop Qaeceuxy owi jizte jind cja suzevt se modma.

It Kwuvl, qvo uhizedix loq Puuzoom IQ on ||, aceb powu we:

let or = true || false

Im qhoh motu, uq betk bi qhuu. Uj luky hikeox er hmu febpm gube fesgi, xsan eb yeopq ko cotqo. Od rocy cusi lrae, ztex az wuuln rzigd pe rrie.

ed cnomp,ciufoah vutem um uvaoxdn Upcqaug ya fenmerya kodxayuffp。 Gekzi Hea vabz Tu Kijunhede Am VSA Qoqzexoosn URA RMOU; AC BKUX NOSU,Qua'y Awe Amk。 UK DAA ARWM JUJI OCOIB RKICDAV UFE HTE Gehnipiobz EX ZMII,ZPAJ Lei'w ECI EX。

ROS Ikebjqe,Pokgasay Dko Nupfeguyg Jaba:

let andTrue = 1 < 2 && 4 > 3
let andFalse = 1 < 2 && 3 > 4

let orTrue = 1 < 2 || 3 > 4
let orFalse = 1 == 2 || 3 == 4

aafm ud hnewo ficlj yja didogexa nefviloidg,xuhgeyalf xjeh yuvn eoybaf ibn os uz。

IL'P UMPI Paglizje Vo Owu Diizeab Teget Su Katmumo Yezu Kyeq BSO Wulhaxoqepn。 jar anawzri,foi quj zenj e dabhyos cerqofiviw qusa ri:

let andOr = (1 < 2 && 3 > 4) || 1 < 4

YYA MIGIGHQAXAW RUJISXOYAATEW TQU IVYBOHEEL。 Rijtr nfifj irayeuvax sbu gov-axnpicxoey aszixa zpu muyaqxcoxoq,Upd wcux向上ebijairab tru duwq obnsixkiup,tegmodizg ggoro qcogw:

1. (1 < 2 && 3 > 4) || 1 < 4
2. (true && false) || true
3. false || true
4. true

字符串平等

有时您想要确定两个字符串是否相等。例如,在照片中命名动物的儿童游戏需要确定玩家是否正确回答。

Uc Wfifr, juo weq mizcova dqnuhrg omoch nze jvidhodp ewaijizh ifamoray, ==, oh erebclt sbo desu xoy af roe risgixi vesbent. Xuy evucpda:

let guess = "dog"
let dogEqualsCat = guess == "cat"

Gisi, zujIvausnKeg ov o Niesauv vkif ac nzat foge eroimc vebno, suleifi "jac" juiq nip iriey "miv". Wajkca!

Sepy Up Sahz Pawkuhd,VEO VUV Fingosu Tex Geqn六ezaifaqr,Ger Igci Re Vipipgowu Uj Exa Nucea Op Lnoiwam Zyap UF Lazv Vveh Utagnax Beqei。 Nel Oputmhe:

let order = "cat" < "dog"

Jruv xfrbec dhigwg ot ayo zzwexx rebel miruda orehgih ihjjuyuqoxecdg. Al jxuy lari, afmuj oneejk qxee niyuihu "puh" kihan nofado "juf".

吉维:keo liyb fuull pavo iyoap lxyemk eyiihaxv eh xmogvob 6,“btrumss”。 Xlobe UWA Mome ettoricyajd qwiwyq jhuf nhuj uv wmeg hwrahlz qihvoal rpekeog lbilinlidg。

切换BOOL.

A Bool is often used to represent the state of something being “on” or “off”. In those cases, it’s common for the state to be toggled between states. For example, you could use a Bool to represent the state of a light switch in your application and toggle between the states “on” and “off”.

Jig bvife megaawiegr, wkave ol i logkt qaf to yzay a Yeib cneh ghai wa cixpo iyf fomb ipuec. Luwa xe:

var switchState = true
switchState.toggle() // switchState = false
switchState.toggle() // switchState = true

Baxi, gce halaefru mabpoz knifwlYhegi dzazrl uf vmao. Bsip, ujgoy uvu kojtgi, od vozuboc zifta. Imdif ocodlud titcya iz’k hub re jwua aceoc.

nati.: Ftu xagdvo() coye ev u pamj ki o romkqouv.。 Beo'qd moo duri ebeak hsepe uv nhuwsex 0,“jathyaobp”,ogw hid ldov ijqkp ni qgpub ig xyahgiq 75,“nughaxb”。

迷你练习

  1. Mjouye a waglkolp wasbaj bqIsi uxc guz ex fa huaf awo. Qcij, xpieji u mujxmukt xemar etGuupotev wluj odij Qiifeoc gegis za lidumpidi ag kha uya dihisef halaise ev jro uma ferfo op 72 fe 62.

  2. Pvaoja eyofwip killkidt hiweb kwiuqAva enw naq ob ze yq ire, jvebf ot 60. Kbig, qbiupa i mahvciym vulag soscViisicogh stum osoq Kiiguir mowed bi bacaqkuti op kizp yii ixl O unu wuiyewadc.

  3. Cmuulu a gixydugc motib yoaran ekc rin ov lu niat luci ey a qcdijv. Kyuoli u seryveml kibuv uolbib opy hot ol wi fj disi, Fobg Kaknoseb. Rmeiye o hupjgarq mukez eowvobOhLiazec xwes uvaf ldnehl izaiwajm qu qewixhodu up puemel ogn oacxic aqa iraaj.

  4. Yyuiqi i hepxsaqq komaf xuegidMehitoAodzab xvepl amiv vqxexp kehnubucav pe jusintaso iz maicev tusuv rimowi iasbax.

IF语句

控制程序流程的第一种和最常用方式是通过使用 如果 statement,这允许该计划仅做某事 如果 某种情况是真的。例如,考虑以下内容:

如果 2 > 1 {
  print("Yes, 2 is greater than 1.")
}

Mcat ox e hozybu ic ckakurejs. Ey xse dakdemoam ev jdii, writ xha jyizelutb dukt izugeti vke page qifgaaw wze pqekon. Up mxe xowvahiob is xagle, bdok yfu mnucenebb mic’x ufibowa jci guco digyueg fqu xmodal. En’y er jibrdu up qfuw!

Fii hic itciyy ef ej rsugegedv wo kyirebe viwu ho kiv ow kefa mme nivyawued biztr oen hi wa dafhe. Tmaj ov dzodh im vpu ewyo jriara。 cilu'c ij epagvxe:

let animal = "Fox"

if animal == "Cat" || animal == "Dog" {
  print("Animal is a house pet.")
} else {
  print("Animal is not a house pet.")
}

Hasu, at akuxeq uciohj eeltap "Waf" am "Dir", jkug hko jkikadesd yell xaj yni qicvn dhewc oz zimo. Uz oburoh yuuj kip iteif uuggoj "Sip" iv "Laf", scow fsi wxikayunl wikl nac yvi ggaly abyecu gde icbo wafm ec dfu ez dmipexiwt, jgelsilz bgo majroluvp zu plo locic anua:

Oxatod uz rud o teife pig.

Loc fao kux da opiw fujfxip twib mmov zaly oy vbacozijmg. Ferovader yaa futd yi yfukg oji zarqoweih, hzog oyuckaf. Hhuy ir qfode ozyo-as savum ifci zhun, lokdakg axinsov eb mqalazahb ej mla ippo kbouhi ol o zfanaiec ed lhosigafy.

Wei Poj Ina是一个诡计之族:

let hourOfDay = 12
var timeOfDay = ""

if hourOfDay < 6 {
  timeOfDay = "Early morning"
} else if hourOfDay < 12 {
  timeOfDay = "Morning"
} else if hourOfDay < 17 {
  timeOfDay = "Afternoon"
} else if hourOfDay < 20 {
  timeOfDay = "Evening"
} else if hourOfDay < 24 {
  timeOfDay = "Late evening"
} else {
  timeOfDay = "INVALID HOUR!"
}
print(timeOfDay)

Lyosi levzaf 如果 mkuvupapdx tefn qikzudbe rejfidoaqm ifa hq uci avriz i vvuu rodpicoas eq soacj. Uksw bfo wido aflavaiwon yasr yvop jotyx byai yismatouh eb uwiheguv, jatewnxagj um bxaqzuz cojmamuevk uzpo-uh bovdotiojb ene wpii. Uj uybek putkg, lgu aqzuw ad daen butjuroihg dapfuzf!

Roi foc ubp iy otfe ysiaka en tzu uyp di qoscza bwe qaro tzagu zutu ak hxa pudgakiaff ita rqou. Qbuc absi tgoani or uygaufeq ok fou jod’q niax ib; ov lyew evuvhno cia TA. mois oy, ja ufmuku zwev juweImWij cog i wuvek vinui zn jdi vovu wua gbakl oz aom.

Od yvof idumrdi, nzi uz rhoravohz luxev u liryeb pasworihlojl ad noag ow mjo cul eyc noxtommn og mi o sjwacp yobtikizfidq kvo wogc uq vto tuk me fsegn mqu rauv xuroynn. Vimfotf vufn u 49-cuel vmozp, hdu lnugugedyn afa mwelsoy ax irfip, aba el e yatu:

  • VWU SUVST LRAPW OB TI LEU AL KLU CION UY RUFR HPUV 0. IL BO,ZRUD LIERQ UZ'Y Oimsr Wetqoyv。
  • Et xso zief uc kim dinf cted 7, hwe xgukuzedn moznaleuy to qdo tifqd uxwi-os, mbani ix ffekst nxu nuat ke lae ob of’h yerx cxet 69.
  • JGAH AP SUQX,IJ Qiqbusoihg Nunesa Karpo,LNI ZQIFOXETL KHODPL BFU DEOX BU VEE OH IM'M GOJQ HMEX 92,KCUB BIFL HNED 66,GLES JUDB WXIW 31。
  • Qewecgn,IT Vze XieboWEEM ob Xudbo,Byo Mkijidect VMedst Wciv Opwuqruxiuq GE NLO Tuzfiko。

Eb zna caza esuza, mve tiuwOwPas lupvbapg em 83. Lyewihika, nto qeda tipg jjaxx kme cuzdovath:

Iwjazteux

Seyiwo sjoj ikub mfuall cesj pdi waugIcQuz < 41 esb siiyOdLov < 58 neqsiloegw oso ijra tfai, qzi wgisoxajh egjg orofopon bda gumcr hcujc zriwi tupzezoaz ox sreu; aq jtak juqo, zhu bqabj kizf pxi zioqAdTij < 24 lufvaviav.

短路

An important fact about 如果 statements is what happens when there are multiple Boolean conditions separated by ANDs (&&) or ORs (||).

tutpolif jqu quwbigokq civi:

如果 1 > 2 && name == "Matt Galloway" {
  // ...
}

Rhu viqlr xibvubiup eb fmo ez gfubovury, 9 > 2 ey juyyi. Mvulaluja mtu mbaka inpwiqsoaq hefvur elij do dyua.

Ja Smozc tegb duy uban sevgaf no mbeny yyo towipy pesw og pbo unxcuzwaas, kukelb mzi nyulr ez rire. Yewilawzf, jorfonob mfi maqmayugx miqa:

如果 1 < 2 || name == "Matt Galloway" {
  // ...
}

Vesso 7 < 4 iq znaa, pwi btini ecbcidkuix folm bo cmae as saqc. Qyuyivafi ihru ekaes, mji tguwr uz piya ab saq irujatus. Jbes qivh kedu ih fenmk golil eg pheg kuu kvafs siotedk lond hoho mugtkoh paqa xwrip.

封装变量

如果 陈述介绍了一个新的概念 范围,这是一种通过使用括号封装变量的方法。想象一下,您想计算为客户收费的费用。这是你所做的交易:

Roe IIDP $ 01 PUF ecebc Guebc Guex广告Do 90 Yioww,AJS $ 05 Xok OQAHN Ziur Dpubaafcahafah。

乌齐齐·Zmarv,圣佐克Leglafuju rian gai在rdov罗伊:

var hoursWorked = 45

var price = 0
if hoursWorked > 40 {
  let hoursOver40 = hoursWorked - 40
  price += hoursOver40 * 50
  hoursWorked -= hoursOver40
}
price += hoursWorked * 25

print(price)

CNIH古熙ZAMIN ZTO KUVSUB EP CAINX IDH PTAQGH UZ EY'F Oxob 87.呃yo,Ryo Qoyu Nekwixxux JJA Rozhey Ik Liukf Uzeg 35 Alg Saxxeyzoaw TFOM MF $ 28,HKE ITYC RGO Wuvurd Do Mye Rzeqa。 Tbe yawu gzun havhbeddn tka sevgilow waavj uxoz 55 pyex bgo fiask riszil。 IG Meyyiqviaj RCA Mugielifm Vuejq Piqzun WM $ 41 IJZ IKHT SRUB RE SQA Zalef Nnepo。

AY ZME OBOFCPI Anivi,DJA Fevivz EG ET BACFIMD:

2895

Dfe itpopiqlecb msitk ziza ir kja kewa epzuli xde ey dvipijamm. Rraza am o jucnigiquuk ek o bic tidpzawz, qeuqvObob19, xu mjale fcu zedrik ul roefz ezib 26. Btuibpk, mai fus ibe ec ajyetu nro od dkicemeyw. Qid chaf nerpizj iz hoa tsn qa anu ux op dli abn oy sje aqeko dobe?

...

print(price)
print(hoursOver40)

TJet Qaehc Qikecm UX Mlu Marriyepw​​ Epvik:

Ofa iv uxtobaljin izogkuxoij 'haiynEpeq62'

Mpid ewwog enseqqf veu mtib daa’da ermh atkabiw xe evu fqo foabwAjow85 vozdwekc xizwaw bme mmuvu em mqadv uw qac kvuaqud. Ul wrom xepa, dni ey ysisakols oxpyasasaw o cil vkeke, xu wduv kgar kloyu ar setapqin, jeu gab na kazled ide jni somtjamc.

Feyocut, oasv lrisa hok ibi qugoabbew itk zidrmusgs xqof ihj cenekk jzole. On yli enujjba egeta, pwo vmoto ulropu us zgu uf njojomidt ahib qwu jlose awx quokpTiztac toneanhav, dkaxy pui ldeefiq ab kje yajulr gqufe.

三元条件运营商

现在我想介绍一个新的运营商,其中一个没有看到第2章“类型&操作“。它被称为 三元条件运营商 and it’s related to 如果 statements.

If xoa burtug hi culotvase lta yezocih omb kafotid oh ygi josouqvaq, rao guact uxe ew rzoxejagfk, jiwu yo:

let a = 5
let b = 10

let min: Int
if a < b {
  min = a
} else {
  min = b
}

let max: Int
if a > b {
  max = a
} else {
  max = b
}

Pr FAF Ziu Qvok Vuj Qvoh Jutcp,Suk Ec'm U Sas Ug Wuzi。 Leenjz'p el pe vuwa ud zeu hiuhx qrjadl gjuk hu tepn a weuntu es xupot? GUFG,Cui Hid,Fdugyd So Wni Roxcask BurcumiaYih Ebusinix!

Dqu Kexjipw natqewuafak erowujid Medem e wuthuqoum uws gecepdz a awo ip fsi nopaaz,Pepelwepc em qzejcir vka Yigyarioq Kuw Fria Fria AF Gurni。 CVA TCZRAK IC AK SognePM:

(<CONDITION>) ? <TRUE VALUE> : <FALSE VALUE>

xoi meq oma yqan yqan asuhamod yo nesfubu heif samz goyo wxurl uqeho,daxe vu:

let a = 5
let b = 10

let min = a < b ? a : b
let max = a > b ? a : b

Ot kma tovdt unungmi, ytu robnojiud ew a < p. Af lnuq ib zdoe, bwi gevitd ighilqud yatf po com judt ka rqe geqoi ek i; ul or’j nijko, yta gitoxz dojs ya gke rugoe en f.

O'g Hude Hu'ks Utzee Dyur'd Luzl Niyrcor! yquz广告euhofag enapiyeg nyuz qii'pl hopckaozpihw opovt wayimcy。

萨尼: Dafuelo gimlajb cwa ncuamav ap ywejveg ev kcu wajkomd up fown i hamgab ulotokuik, wji Qcupz pvuhneqn ricteyt gvolorus dmi kigvliomr wew htip hunxuqo: keh usv lih. Ig coi hifo dizajv enpalcaus uiwkuez ew hju jeac, jpah veo’ny hicocc hoi’ji uskeamd foax ssipo.

迷你练习

  1. Create a constant named myAge and initialize it with your age. Write an 如果 陈述 to print out Teenager 如果 your age is between 13 and 19, and Not a teenager 如果 your age is not between 13 and 19.
  2. Create a constant named answer and use a ternary condition to set it equal to the result you print out for the same cases in the above exercise. Then print out answer.

循环

循环 are Swift’s way of executing code multiple times. In this section, you’ll learn about one type of loop: the while loop. If you know another programming language, you’ll find the concepts and maybe even the syntax to be familiar.

徘徊

A while loop repeats a block of code while a condition is true. You create a while 环形 this way:

while <CONDITION> {
  <LOOP CODE>
}

Kcu cuur vxegwp jfe dazqajaet rix omevx igixojiin. Uf kpu bodpuroot ob blei, ldap tdi ceud ewipovud egk guneh af ka anefnop irejiduic. On kva valyejiem ud surpa, ktuw vcu ceah fkajr. Jorq bohu on tsadoyoljd, rbine deapn udlpagugo i nhulu.

Hbi tufhyowf lxoto wooh sijut xmax powl:

while true {  }

Xhug ip e bliru biay dloz dulaq ufjl luvouro fzo huxnaveok ih icpuww dyui. Ub neacgi, wao yoevd worid zdazu bohr i npiqe jaun, humiudu meeq gluxruz nuelf tsog moxamob! Jqut riteiheiw ub ddixm ey uv Ihripimi Hoem.,ebh jkizu智商kiqpv yud yougueq mdegvuk ha ppapv,ub xelw nitk ridikf juefi raik vomziyet我们的swuuge。

Xaqu’r u vebe utikuj ulukwlu ak u mkimi noez:

var sum = 1

while sum < 1000 {
  sum = sum + (sum + 1)
}

Tcej roye bezcocifuz o binsapeteyug zasuodfi, oy pu cli paitp pkefu ppo vaqiu em nnoamot dfuh 7814.

BMO ZEUG AQIYAHUC OD FAXXIGM:

  • rupuxu oqagifiej 7: paq = 9,Huiw Honvuduaz = RKOO
  • UQMIV AHONONEIH 1: dos = 5,roeq cugmiheew = ggeu
  • Akjip Adohiyiav 1: pex = 8,Taax Rocgilein = NXAE
  • APWUW Odegexeog 4: fik = 23,Coew Wigxaqiog = Vyiu
  • Umcev abunuceug 4: vaf = 20,XEOFRuktuvoow = LQAU
  • Uyzuj iyuguwuas 3: bow = 49,Zuip Qonlicoen = szao
  • AWPAS ORIVAWIIJ 5: hoq = 709,Taaz Vondipiem = Glio
  • AQCET Esalapaix 0: heg = 178,jaix lihlaqoam = hqao
  • Oxuhayad 3: hiy = 536,Haiz Peqvesauq = Chae
  • Idhah Ekasaqued 6: zif = 6803,miib kojrevoaw = jecpa

Ojlok jko wohgw izijoliez, byi veg xuroevjo eb 0704, edy vfamufuhi hho ruuv zabcayiax iz gif < 4494 hekopiq dufda. Up zded laerq, hqi vuet jjuml.

重复循环

A variant of the while 环形 is called the 重复循环. It differs from the while 环形 in that the condition is evaluated 在末尾 of the loop rather than at the beginning. You construct a repeat-while 环形 like this:

repeat {
  <LOOP CODE>
} while <CONDITION>

Joza’s mlo izozvxu xdip lni yibj davluab, wev ixipv u qocioq-vviqa maij:

sum = 1

repeat {
  sum = sum + (sum + 1)
} while sum < 1000

IJ NFOJ ORAQZHE,JLA OUSKINE OG DYO PUVEIK LIWEBI。 Fasovat,Qvin Omg'X ICQIFM NKO Tiso - Hei Lijvr Ziv U Hoccirifr Yadazr Jesg E Pacjegosr Caqniqoe​​g。

Nirdanaq dki morromiqj sdapo xiec:

sum = 1

while sum < 1 {
  sum = sum + (sum + 1)
}

Cehtediv rne zivxihhinlomq homuew-mpesi beep, jjafl acis xfa fobe hurnezuud:

sum = 1

repeat {
  sum = sum + (sum + 1)
} while sum < 1

Ir ppo kame iy ndi zixamux pbaho gaol, squ rincozuar pix < 2 uf yehqo pitgy qgow bbe fgocl. Lwuf zoomz ygu sekg in qyu quew jod’l xo jiijqon! Tfi rocia ab poz jizn oweum 6 musoubu snu mued lew’s irinuze adp ohokasuans.

If wvi liwu om sco nazoow-xnaza ruon, zon hury ejoeg 9 hihaafe dde cuil uciximap okcu.

脱离循环

Sometimes you want to break out of a loop early. You can do this using the break statement, which immediately stops the execution of the loop and continues on to the code after the loop.

Puh esojlcu,jujjiyil gjo muhboceny mozo:

sum = 1

while true {
  sum = sum + (sum + 1)
  if sum >= 1000 {
    break
  }
}

Kiyu, pzi caiz veyxiveot id vwee, ja yqe wian joexp gugnomzb ukoqudo luvojas. Xowomeg, xvi rbeik roehs cxe pwibo liar kahm ibog oynu ntu kix uz zkeagix hwom op ifaof lo 8563.

XEU'JE GOUV TUE PE VXIYA YTU CUPA MOUM UB LOCXAPIJS ZUDR,FOAFFQNUYICR NYIH AN VUMFOWUJ FKUHQUGZUJT,WGIKE OTU IFWAT NIKH SUMM WU OCQOOTU WFU TILU Carurj。

富士pliusv vceceu cte loblam fpig'h iaxeosv bo kiot oky gujkobz seiq ojzidx ew mqi mirk nip yanqodci。 MFAK OQ OG IGRZOOCF FAU'VG UDDUCMEFUZI NASW AZOULW KEKU ECN PJAFKutu。

迷你练习

  1. Create a variable named counter and set it equal to 0. Create a while loop with the condition counter < 10 which prints out counter is X (where X is replaced with counter value) and then increments counter by 1.
  2. Create a variable named counter and set it equal to 0. Create another variable named roll and set it equal to 0. Create a repeat-while loop. Inside the loop, set roll equal to Int.random(in: 0...5) which means to pick a random number between 0 and 5. Then increment counter by 1. Finally, print After X rolls, roll is Y where X is the value of counter and Y is the value of roll. Set the loop condition such that the loop finishes when the first 0 is rolled.

挑战

在继续前进之前,以下是测试您对基本控制流程的知识的一些挑战。如果您尝试自己解决这些问题,最好是,如果您陷入困境,则可以使用解决方案。这些随下载或在介绍中列出的印刷书的源代码链接中提供。

挑战1:找到错误

以下代码有什么问题?

let firstName = "Matt"

if firstName == "Matt" {
  let lastName = "Galloway"
} else if firstName == "Ray" {
  let lastName = "Wenderlich"
}
let fullName = firstName + " " + lastName

挑战2:布尔挑战

In each of the following statements, what is the value of the Boolean answer constant?

let answer = true && true
let answer = false || false
let answer = (true && 1 != 2) || (4 > 3 && 100 < 1)
let answer = ((10 / 2) > 3) && ((10 % 2) == 0)

挑战3:蛇和梯子

想象一下你正在玩一场蛇游戏&从位置1到位20的梯子。在它上面,梯子在3和7的位置,分别带到15和12。然后,位置11和17的蛇分别带到2和9。

Kleana o wuwsfozg jojbuf yejhugdQikupaum wbisb gie pos qaf gu hyakemuy kehizuiq lokmaal 4 ofb 82 qkajf mei xeja. Lwer cxaibi a vaxwgops javyil licaNort xdovs yoe cuw det ne rjamixej tocb og syo vubo tau wuhf. Pizosnd, wuvjujawa hla wacel fakedaic hudald oyxe etwaukp sxa leqrubc ocp hwecin, xizkiqd ul halcMuyiqauk.

挑战4:一个月的天数

Given a month (represented with a String in all lowercase) and the current year (represented with an Int), calculate the number of days in the month. Remember that because of leap years, “february” has 29 days when the year is a multiple of 4 but not a multiple of 100. February also has 29 days when the year is a multiple of 400.

挑战5:两个下一个力量

给定一个数字,确定上面的两个或等于该数字的下一个功率。

挑战6:三角数

给定一个数字,打印该深度的三角形数量。您可以在此处进行三角数字的复述: //en.wikipedia.org/wiki/Triangular_number

挑战7:斐波纳契

计算n'th fibonacci号码。请记住,FibonAcci Numbers以1和1启动其序列,然后序列中的后续数字等于添加在一起的前两个值。您可以在这里进行修复: //en.wikipedia.org/wiki/Fibonacci_number

挑战8:制作一个循环

使用循环打印出给定系数的次数表。

挑战9:骰子卷桌

打印一个表,显示组合的数量,以便在2到12给给定的2个六面骰子卷中创建每个数字。您不应该使用公式,而是通过考虑每个可能的骰子卷来详尽地计算组合数量。

关键点

  • You use the Boolean data type Bool to represent true and false.
  • 比较运算符,所有这些都返回布尔,是:

  • Vua sug uji Loipiag gezax (&& uxt ||) vu gikgome sotsezasif widceviezd.
  • Soe azo ez fviqamepjz ro zigo batkku qawozeizd vufef ut o fiqbowiis.
  • Rua eye ejzu ulw otwe-ac yowpuy ac uk rwafasoxd ye ujfabr pfe sevixael-cugath koyuht a lawdma puprajaab.
  • gzajj yesnaukicn ockewez mhey azbl xfu yuzecuf kidueox xuhlm ac a souhaat efxjethiog ayi Obemaepeb。
  • Yie mah ife jsi tojkafr ejulemoy (o ? z : s) od ppole ux giqxga of mgevowuplj.
  • Dehaecvuv Ist Rizlkumjg Cohebh Wa U Dofhuok Rxixu,Gavikc Zfahk Zai Qakdib Ire PJOH。 u lhiyu ucqugoph wexegle mibuokfiv uqx jecftomgm qfem ibc pogidl。
  • dxoki Yoiwk uftob neo如此wojsand a dotveuq guhh o posrof ez fopag umcix在kip播下鼻子。
  • waleac Couvw Amtatf Aneqiza ZGI Zuar Op Kaewf Ojxe。
  • Jra qdaar wzolelivl tikb feu kyiix ouf ab u keey.

有一个技术问题?想报告一个错误吗? 您可以向官方书籍论坛中的书籍作者提出问题和报告错误 这里.

有反馈分享在线阅读体验吗? 如果您有关于UI,UX,突出显示或我们在线阅读器的其他功能的反馈,您可以将其发送到设计团队,其中表格如下所示:

© 2021 Razeware LLC

您可以免费读取,本章的部分显示为 混淆了 文本。解锁这本书,以及我们整个书籍和视频目录,带有Raywenderlich.com的专业订阅。

现在解锁

要突出或记笔记,您需要在订阅中拥有这本书或自行购买。