作者:Thomas Hanning,原文鏈接,原文日期:2015-11-16
譯者:pmst;校對(duì):千葉知風(fēng);定稿:千葉知風(fēng)
借助于 map和flapMap 函數(shù)能夠很輕易地將數(shù)組轉(zhuǎn)換成另外一個(gè)新數(shù)組。
Map
map函數(shù)能夠被數(shù)組調(diào)用,它接受一個(gè)閉包作為參數(shù),作用于數(shù)組中的每個(gè)元素。閉包返回一個(gè)變換后的元素,接著將所有這些變換后的元素組成一個(gè)新的數(shù)組。
這聽(tīng)起來(lái)有些復(fù)雜,但它是相當(dāng)簡(jiǎn)單的。想象你擁有一個(gè)string類型的數(shù)組:
let testArray = ["test1","test1234","","test56"]
map函數(shù)的閉包接收一個(gè)字符串(類型為string)作為參數(shù),原因在于我們調(diào)用函數(shù)處理的數(shù)組元素類型為String。本例中,我們想要返回一個(gè)整型數(shù)組,逐個(gè)對(duì)應(yīng)字符串元素成員的字符長(zhǎng)度。因此閉包的返回類型為Int?.
let anotherArray = testArray.map { (string:String) -> Int? in
let length = string.characters.count
guard length > 0 else {
return nil
}
return string.characters.count
}
print(anotherArray) //[Optional(5), Optional(8), nil, Optional(6)]
FlatMap
flatMap很像map函數(shù),但是它摒棄了那些值為nil的元素。
let anotherArray2 = testArray.flatMap { (string:String) -> Int? in
let length = string.characters.count
guard length > 0 else {
return nil
}
return string.characters.count
}
print(anotherArray2) //[5, 8, 6]
另外一個(gè)與map函數(shù)不同之處在于:倘若元素值不為nil情況下,flapMap函數(shù)能夠?qū)⒖蛇x類型(optional)轉(zhuǎn)換為非可選類型(non-optionals)。
引用
Image:@ Fly_dragonfly / shutterstock.com
本文由 SwiftGG 翻譯組翻譯,已經(jīng)獲得作者翻譯授權(quán),最新文章請(qǐng)?jiān)L問(wèn) http://swift.gg。