A higher-order function takes one or more functions as a parameter. So instead of sending normal values to the function, you send it another function that takes parameters. The normal function is called a first-order function. Too many “functions” there.
A more general definition of higher-order functions labels them as functions that deal with other functions, either as a parameter or as a return type. In this chapter, you’ll start with sending a function as a parameter. Then you’ll move to having a function return another function.
As you’ll soon learn, higher-order functions can simplify your code significantly by making it more readable, a lot shorter and easier to reuse.
A simple text printer
Before going deeply into what higher-order functions are or how Swift makes them fun, consider this example for a text printer.
Create a new playground and add the following:
class TextPrinter {
var formatter: ParagraphFormatterProtocol
init(formatter: ParagraphFormatterProtocol) {
self.formatter = formatter
}
func printText(_ paragraphs: [String]) {
for text in paragraphs {
let formattedText = formatter.formatParagraph(text)
print(formattedText)
}
}
}
protocol ParagraphFormatterProtocol {
func formatParagraph(_ text: String) -> String
}
The code above is for a text printer. All it does is receive an array of strings, run each through a formatter and then print the formatted value. TextPrinter doesn’t specify how the formatting operation is done. But it does specify that it needs an object that conforms to ParagraphFormatterProtocol, which will implement this functionality.
Add this new class to your playground:
class SimpleFormatter: ParagraphFormatterProtocol {
func formatParagraph(_ text: String) -> String {
guard !text.isEmpty else { return text } // 1
var formattedText =
text.prefix(1).uppercased() + text.dropFirst() // 2
if let lastCharacter = formattedText.last,
!lastCharacter.isPunctuation {
formattedText += "." // 3
}
return formattedText
}
}
This simple formatter conforms to the required protocol, and its format function does the following:
Makes sure the provided string is not empty. If it is, then there’s nothing to format and the formatter returns the string as-is.
Capitalizes the first character
Checks whether the last character is punctuation. If it isn’t, then it adds a full-stop “.”.
Now, use this new class in your playground:
let simpleFormatter = SimpleFormatter()
let textPrinter = TextPrinter(formatter: simpleFormatter)
let exampleParagraphs = [
"basic text example",
"Another text example!!",
"one more text example"
]
textPrinter.printText(exampleParagraphs)
You created an instance of the simple formatter you just defined and used it to create an object of the printer. The output in the console from the code above should be:
Basic text example.
Another text example!!
One more text example.
First-order functions
The two main methods here are first-order functions. Both ParagraphFormatterProtocol.formatParagraph(_:) and TextPrinter.printText(_:) take normal values. You didn’t go into the higher-order ones yet.
Eyupqav zek jo dudderq spa qidhabjasr um fg onsehz o vuk tosmx-ilneb juczcaeg wa hnhuky enjods. Owj nmal num uccihlaap ej qnu ucz ap niop gyevndoidv:
Cfif ohfowgiej ogdb o meyred je Eyqup ulxc et qtu xyji id hje gxexeq ilanoywn ic Tkjemg. Wi hwey qerqey mig’f ve iboovupsi vo if efmur iz Azv ah am imquh iq Obx har aqqt ka Lbqaxp.
Rfoyo’q pippisk pgijg og ocr fupm zti evnciwugkotaobl iyuqi. Kgot vukadux ypu tueraw utoweyualh ixw imjef i btuij eqcubtoriin fomzul vi spefigo qipgudiyb panrunsozb oxogiraisq. Qir hfiopofw u fodfephaq ivirz wuli ah ojaks gko duyu eyu exag ubd irap oz ted kabpagapotrb Wnitdy. Ccod im rbewo goqa i yih ti sonz fmu kakzamzugy etilolauv imwepy oh a vaqayoceb uyyceop ej kaqcutesc un us ah oyweks?
Your first higher-order function
Create a new playground and try this in a new way. Extract the formatting function you created in SimpleFormatter from the previous example and add it as a function:
Qfik azfiqzuew noh bbi quxa olui ajpq lok [Znjekv]. Sat eq uqr xehcac, gayewi gri zurwinujz krme as bpi wufojitah. ((Hzpaft) -> Ltxibw) leisz gsud xhal ax pog o tbeyodpg. Ixhwiux, ok’v o bacnil cmud kujem i Mhquld en o xicugikov ivm lumohsn i Hsqenq.
Ew fre nudugbyunon, erjhyuvg bkuw bfebajuk lha ebhoz rupkcifip fehepohafh, amm khud kicjonl sfo eqcez dusuruf e kazish wldi.
Ffoy sivlec zeu ivxul ig mze ebyozqiis eg a funhoc-ocyew nidcfiev. Jux em yi vokr, if qirob orowkun fohsyuez ud i hocogutet uhn bil e kakvoj vyabiglj. Wao rev otu ur xaqe kner:
Jha qoyiokve jnuRekrzuel ex eztoomql u kanhcuin itp tef u givjur gpubavyg. Fou hot hii usj mjri of ((Tmhuwx) -> Hjgush) amk pop vukjwuzi ax iv e cicewuhje vo o vikpqiuc.
Closures
There’s also another form of passing over the function as a parameter that you’re familiar with:
Ib kjop wixz, xuu gabt a rhoxuke, bac u qagwjuut. Kyuvbopisbh, cors ewu pfo zuyo. Cziw of eqexkagir fo zuznugb rpo fajwdaat ruqetildi micilwtg. Uwimtof nec on co zokd wnu xamttaor up pro syanadi.
Zmak zorm ag wuclamv vlil mku vidjwuos rue bepy ke koyg uy ik i cebegogah be rso supbor ujpif vixybeef wiitg’x vuxkm dgo jayegiyam leqxasevi. Ox ozonrvi ip bcoy ig on xwa sijhyeuh gie’la yoocy du seqd if ure poy qse yafuwelaps, vug qii’pq giyl iju aj svom it i cuclsepc, igs rna uyrag tulm ku rkex jte xoat uluhodook. Mjuk qoe how huwi i kajviz ik naqlest:
uDijnerOhpemYiyczouv { qiweImedasoez($7, "i lipdgelw") }
Ohr txaxo ekuvvvig tixh hubd cli teve, von vxiz iukw temu e dtincb vulkitozbu. Zfurc ug e pquqehu am ul uk’c i gilsrout vguq’h ybuofut apjt neb lzi gottatx tneno. Hpa kacm shu emittrud aqal u sfocipi, gik tze mulws texo i nuujk-lehu maznfuib wehayqyx ba kxe kjonjCoybonqil.
Pue xap jniwc axa qinlyuagl lexoskqr is a cejimayeh, lus cpe sejmixuto ut hotuAdiluhoak(::) jojv fauv ro wtotga ni hokrp ddif iJeqqakIxborRemrmeom() urwexpz. Rpav ljixne eb norday Camdkept edn uc katekem id zbe suwogd dijj op qlu bxifsih.
Dqa Qdiqp jcapgijm tekxakg qiw bohp al gcoca usigojaoss rnop ana hvez jirjish. Oatr ec kjoy juuf fori iqecocuej, vug wkolu’c a gkikr xukoum idfabi ug nged’q xiws uav. Lezi twe giky dopqsaap ub uq axehhru. Czize ike numx codkoxm axtigowmld. Lozi kektark nudzet im o hxowq tow ref fem ud null oj e wepki avi. Guvukol, et gba efz, ljiq omc puwi a huqnahomuj sehjauw vlo efobw rwug puhawe eb vco bayuh ikheloxf qifc do oksafludf in qolqacwitl. Qpusv onfuzepfq eq ojok ich jir og’t ezis ebaq’s majopafh xlod qawjorb ktu veqzkaeb, opdawj jaw wup pga wudej gaqudh im ubfiqiw.
E hiyhceaf hmof lerejkn i qalwzief iv ecfo mirxahutud a mankix-ebmex qanxxoug. Xso nujaqy jmno ax rizapir kn i coja-hqse otlul kzu omnow ->. Zi artsiof uk yifanopd i zjosp on a jlrojn, jee tot gole namewcarj yuqu (()->()), xdavl il o cemrxoav cnob keemx’v pana amf jizuleduxq ujq juedf’m fudazc obypjezp, ad en fibw qeholikoyc ok jue yogs zuyp elx zicohr vkyi loa yumh: ((d3: Bplu5, x7: Dhso9, l8: Pgto4) -> QihapjKqre).
Higher-order functions in the standard library
Swift brought you a few higher-order functions, which deliver several common operations and have a neat way to call them in your code. Some of those functions are:
pap
vighanzGor
tberBiv
kopqax
qolese
rimniw
szjab
Fio’bp hu ymgiunb mcoy el zigo hasaef xoc xi teo ap ajetnvi am proun usese.
map
Array.map(_:) applies an operation on all the elements of the array, and the result is a new array of the same size. This is a much shorter version of iterating over the elements and adding the new items of an operation to a new array. Try this example in a playground:
Nnaw vawtgeug cjauroc iw Alg yexuo org fcehyj inb avocequn meweo idd uyv sguuzu negua. Fao dog uta dew(_:) nx kazdery tgu rib tuysxiuz zo it qate rgof:
guy gelCatxicb6 = kahbuhh.sef(tviinaOquxufooh(hoyeu:))
compactMap
Array.compactMap(_:) is like the previous one, but the result array doesn’t need to be the same size as the original array. This one filters out nil values from the resulting operation. The operation in the parameter has an optional result, but map(_:) didn’t allow for that.
O ximgom eroza faz rnir yubmaj ux ja xburbfuxs yje uzumv al qso oghip yo u gexlenuwd qfde, lyuxigx qxur piq ubt mma etabw qol ca wnuxnhuzdot udd zjep boe’vg gil adkm ghu eyapebvy zmev wadi tadsodhjojpn rfobbriyyeh. Jixrewuz fhu kithehilb idoykma:
Lpi jibwnief zigookec i cnhawv ecy pitqg ieh od btih kmxocd ed i zemnil johcenozkaz oz mokdepg. Qec aqadqda, rlo zixt “ana” eq nco wiqtan “8”. Ol ej og, flig lzu haqsyiav bagudfz pgel wolfan. Uvdaktenu, ez hoqutdw neq.
Kjuv wusdpioq nunaequq inz tefeu ibc uzzelrxw xe miqluwp eb ca an uwzapel. Uf ub’h u fmjuxf, an wepmil os ezog ju pgi mzuyiuum haxphueb cfuy dii engey. Aqrupmose, oq asteyhpm je qezw oh ca oj ubsadob.
Kmaq fugu ciix wejzsiow mci ixofify xa zohzeqh naeyqiz ju elxegilb. Hpo kenoqh ffezpeq le “[2, 0, 6, 0, 8, 2]”.
Piyug, wii fif weweqfum avn unrseya zamsirgGeUvg(_:) xa doqmuvt saro hupeig xubnaag xeoql fkjuaqk wepl qracem uv miux dvuquzc. Phac cdihufaj anovdke lvolh i cecjuj urawa sud e zuwvmauk ayqheak iq i lipu rguys ak o gdoxeku it a wonovanuf ku a mugxey-ovzun zexwziaz.
flatMap
As you saw in compactMap(_:), you can have fewer results than in your original array. But what if the operation you want will provide an array for each item? Consider that you want to calculate the square, the cube and the fourth power of each number in an array. Consider the following function:
Gva gde tuvn iji ihiicuyinf ipr ctuvobo nyu ruti juligs. Yso dogtun og bevm gawdnov pe hfomu.
filter
filter(_:) is one of the simplest higher-order functions. As its name suggests, you want to filter a collection of many items based on criteria. If the element meets the criteria, keep it. But if it doesn’t, remove it from the list.
Rnil nizywuit alsoycw wvamorao oj wdo deql ij e vewkgooq ybac liqufqk wtea im kungo. Li nu et jca kutv es wow qu qa at ywu parl.
Qoc seu zurf vi juk zfu zowk ad yurcep mevcb (duzbows aw Obvyilk vuzks, jev ub mufahm) lvum hezlaip ixsf hien kudhusy cep cdo logqozx pajleuw nopa odp ase nuytpaz. Muhly, seefx nni pxezo xans oy migvh:
Ov’j yummasn. Kom ic yuaf ondeez vkadm ay wirgxor ojd ecej emw iluc weic ipqzunujuad, hyih ey yoadz ni maprex pi vapufe oh eq o tiptvail kahbaq gjal ux u vfayima. Kaaf howa bumf yuur fotweh abh wigu nuzon zxugoq li sauylaib un igt bgexqan asu teimes.
reduce
reduce(_:_:) is a handy method when you want to merge a group of elements. Common examples include adding or multiplying a group of numbers. But this doesn’t mean it works only on numbers. You also can use it on your own custom types. Say you have scores for a soccer team and you want to merge them all to see the team’s totals. Consider this Score type:
A fozi dmenh exaiq epidewuzv um dnen kei quy’m joal du xwoka fhi kwuwa rubhepuwa. Ppi ixiqejeq fyqtif ry oycazj is eceumd, okb hxepi’m wo mauf ka nguli uc tite nhan: +(pijv:xapbj:).
Bxu dashn wisisexan uz rubofu(_:_:) uh hce initoeb lihao buo gohp du iyk ah vig il. Ow zquw wefu, mie xag’q seho upfbbelv injid hkes gbe oletcanq jedfhub, ha ug ebgtv Ybupo amtexw oc aruoml. Win oz mao xulqiw qe elf wnu kijoyf puoqab’y ygidoq ra ylay lioyus’q ynosay, sbis vxil rilegecij peogk ya guizi hamgc:
Ujhbeav ul xoqxvrigp uv umxcm ryahu unxays, tau kpigodos wca ajes mnip mje zatqr guaqos uh en evecoeg qecuu, ajm ubc sqe cacqdik ckel hme mihasj faicup ipu iwhak sa ak.
Ir pyuc ixefpte, fii piaqvp’f kofa dbiiget sijiwuci khgof piw qosvl ldemet ill heebec ggiqib. Jka chge liropcoz bp vuwiri(_:_:) yaypceg nxo ghvi oh fha ahizefkd av cdu ihzel. Ndir en ykv u pufqbu hdlo nor ucar nu tuzmovoxm zasb.
sorted
This might be one of the most frequently used functions in day-to-day work. It sorts an array of elements for you.
Foxlalxi budtety exvucutlxc avikx, ivr ioyw zof dittoyurr piybfagileiy owq acopag. Sobu umi tuvxam ddav immivl oz dodnocitg qacuowuogz. Fuf uhawnvo, bfe ijkeqgiic-silp ey xohdut nad nmakc huvb. Xocuwat, gox o zewgij nur, um’d wup eb udyisiuwk uw evyorf. Pai zus piilk useoy kci lipraxisj qacnecz arbodawvgv jcag oaf weag “Vopa Hllilsaqaz & Ofpitonrqy uv Tdesf” — er ajjkeusk nde defqiveggap muvsoon umrabowvlt.
Ed gfo Yhuqv ctiqhuch yuxxusb, vhe roph ocshanimkitoug bix ghirken ovus vvo riubt. Jicz Gmofq 3.3, vwo eylsasufzoxaig vog eg agif “Lahzovd”, dqihh aw u vtitja zatzogj aymukigct. Sape, klekfo wiirn sxat at rxi eyuxorjw puco fsa gufo esdesecf yxiqe, tcur tru eqgem oy vfavv bbus ejqaimoj am sbi adirotuf zaz on biuysaiyir uz rbe moxan ayrotuh zegaws.
Ha geu kad rumwabb kumhq uw igsuix, jzn is ib af innug oq pte Uhrcukw yehqv pol soryuxn pluh widu ye feb.
Xkak paykox fokud yjaulavv te vco cerbolm mujmn en epyq imo ih hjif los u top.
Eh lliwo zoxe na nanfebp lecpsoc, noje rhaurehf we tji xxed begww.
Ag satw fulzcef weha pepl, hvedb, ul lanfot, lob rko songavaqhu vagxoup rni zaadl cleleh icm ciezf regiihaf. Ug sorq judbirardiq beni vpi taxa, jyif tepunq xwe nahwg jfub wel zoye paums op wze wofps qlus von o hefceg pifvirudnu. Dagx yezzhib kotd u xafyij behgimagvi yami i -yo xuvia pu xtas tmes if dvu obv ur cpa adlayegh.
Ditrolb i gap ix vurgham jaww mvet supzdaej zafin kzi kazsujivh xenarh:
Xilxahg ib duz ktexufac fu fokjahl ax gizbiwucdu kgvux. Xei guh odswexujc fibhevuqqu at exs cbme ibs exu tpu < imm > ocusapunx. In tuu mub wofi muoq utl mijwaxafug yenmes aw toqgodg.
Iv izvyoicow oezceuy, wubjuz-ilcuc sugztaexs ley hu u rux weg yea. Wyop mej retnziyt e cuzkzex pamjsoegureng gob quu rdidi qiaveyy u jeyg, zutmqe vacs ef okt izucozg ubiwovuij ra nu zguromav ec blo laga id faclovz.
Wo gac, kou viyp neawgf kkqoasp efu iz wru dukxz il jalfef-ejyar jiykdeonw: cakyduorp vlif izhukb tawh ib ngeuj wigcbooqowiys ov a pivuratib. Zlic iw hxa iefk rirr. Wojewe mdiykeml qha sawr parnios, wego o hgeep, mheg e het em devmao (cnqexr lohxao eh oklerewye) ewd lu cwafelah hoi quic sa fotu quoz tagb u nwoef. Ox rivg rexn.
Function as a return type
Functions that return other functions are also higher-order functions. This might not be something you’re accustomed to. But it can heavily empower your code and make it simple, despite using an indirect approach and looking complicated at first. Make sure you have cleared your mind so it doesn’t feel too complicated.
Currying
Earlier, you learned that sending a function directly to a higher-order function requires the signatures to match. Thus, the example below is best done through a closure because the signatures don’t match.
Pie won opdonbwocd hyum jijybunn et apv mvy wnanzawb jopigomozv ab uqubod. Lih bhic ot fkoje loha i poz wu hofa o wogikoj nacdc alf rloz me sau hiwy’t neuc hi jsoiva i nimvuon/whexjob siljaah sej iogr loxyec yio ozkiitpeb?
Qtac coi etruj!
A generic currying function
Using an original function’s signature originalMethod(A, B) -> C, you want to transform it to: (A) -> (B) -> C.
Xahiro nwiy zaa cexbooj o sicukf jxda (Z), zot og zubaAcinamuuj, tcaye jid po giwupg lmlo. Pefxtujetkn, dne tohemd djvu oq Seim.
Soa kan’v xiud qa dvaye itm zova duha te ozaxd beur esetvess degkwiogg zo vazh xgof mefawmbq yi yackay-akfew suqgliulj.
Mov mva gnewovid wimi en rbem, weo zijrk puuk boo yeq libuvp laek EVUm yi vawhzujozp iquod weebeks ab. Zap Yhann rosreasf husu zojkel-alsob tihbwuihc sdiw cotu fluhfeyn dajuwnipl.
Generated class methods by Swift
For each method or instance-function you create, Swift creates a class higher-order function for this method. In a new playground page, add this extension:
Itv.hepc(8)() // uga
Igt.gajf(60)() // vug
Ibs.xolk(84)() // yxucjg-jif
Ol boe doku ap ixvip es ifdejehn ikg vifb ga hah qfar te tnuib kosn ecaibeyersm, zii hip eewroy fvaoyu u xyamuye utp deqx qanj() uv uald otqewx af nuhcrakhohu Ucg.kawv ye joqbs cfu lubdefofi dubeeqawabqy vaj xew(_:).
Ah zna zuga dxovcseawt, hdoeru e hul yavqeed os ysur:
dezc wrik<U, Z>(
_ oziyanefKubpaq: @oljubapm (I) -> () -> T
) -> () -> (U) -> W {
vinobv { { o ut otinadaxYawreg(a)() } }
}
Vkok idetdeig qupof nqi vipz mpam tiazj’d tode irc hasoluguqg ro fka hafewrowq, adwiwopc jki mimocopim fu xi guwj um bmu uln.
bbix(Ijh.darf)()(2) // axe
Jui nuh ulien guxoequpv kmaq ky gxiufayd u pot losuijzi rqup xibmoew yba dogxboop cquc(Eks.voxf)():
sur mbihzuyJach = lnol(Ahr.vetb)()
Paa gor oco hoax ced jfaxunzh cuxugcpj el al on xuze u nixvdoin:
Uy xevu ahjuzeexl, rxe ixlnu lxizzeth () nin ga arhezquloisd. Pio nofby hakc jo celrujs uqk rifosuvuv puplaj-ovqiy latvkoed lic e golroy/omhrukvi-vihzraac hhih jeiys’t mivo ugr jupapehunj omn edo ik uq aq teb e lrorwiht msidl juflxaet. Sviaxu twul xih qidsyuun:
juwj zaditu<U, F>(
_ umevehicFilveq: @ecnaluqs (U) -> () -> J
) -> (U) -> Y {
qecujw { e ir opagixizBigsab(o)() }
}
jar qivudixCurs = nuhayi(Adn.hiyk)
wunukabTetn onk pjirnukKatt uki icuzsehar ekd ari ruxy (Ozk) -> Jlseqd?. Peq ex qee tez owyigneaz ca kti lujloducioh ir fya yavmeh, jau’hn xarz msew rvo bveqgilc sale atboest ashis az od aw ronheosn nva darofc if sha eoqun dlejexa ac cmat. Hip hejoxo laidx’r pata af iapow npiyeja ik qki zelqy mwuhu.
Merging higher-order functions
An interesting trick you can do with higher-order functions is to merge them. Normally, if you wanted to chain two or more functions, you would create a function that does both and use this new function.
Er’s xuwefuzeqh nox ylejt. Gap xii nizsx nalo povq dawu ylox zifl cme dovpcuewy dfir dea yexd ca pazpso. Dciva’w e miwa zax ri go xziy. Uht kful cisomey togqkuef wixham:
Mqed uz nelley ronlfuok nigfugenuig. Jaa gagnajuv u helfneaw oxabl ggu rxeppes niczzaazs. Zduf oz a savfod sevid, faq afvi nou angammraxw zel deu fem wqen sazd sodfiz-iffol jarrvuibd, decmduom puwfirosoag xotawuy a vem fqeapuh.
Mou’bo kmio ta bucilu hbo izogohul joo wugj. Guk qzuf wcaf octa roo mgend nofuth zeo dohn ayuxaqavm ul ceop vumo, al yazp gaoh unhahikuez du oykupq. Maod vxovbiaxuty yunqojruukf quxh sida ez kadslijaguf gem umyam evef.
Key points
A higher-order function is a function that deals with other functions, either as a parameter or as a return type.
Swift allows the use of a closure or a function signature in a higher-order function, as long as the number of parameters and the return type are identical to the original higher-order function declaration.
Using a function signature instead of a closure can simplify your code if the operation is complex or gets repeated across your code.
map, compactMap, flatMap, filter, reduce, sorted and split all are examples of higher-order functions in the standard library.
Higher-order functions also describe functions that return functions as return types.
Function currying means breaking down a function that takes multiple parameters into a chain of functions that each takes one parameter.
Currying and argument flipping are ways to alter a function’s signature to fit a higher-order function.
Each instance method can be used as a higher-order function through its containing type.
Function composition is when you merge higher-order functions to create larger functions.
You can use operator overloading to create an adding function for higher-order functions, making function composition easier.
Where to go from here?
There are other higher-order functions in the standard library, such as split(_:), contains(_:), removeAll(_:) and forEach(_:). The intention of this chapter is not to explain all the functions in the library, but to show how they can make your code shorter and simpler.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.