มารู้จักกับ Higher-order function ในภาษา Swift กัน

Programming

มารู้จักกับ Higher-order function ในภาษา Swift กัน

3 เดือนที่ผ่านมา

2 min read

Table of Contents

ในภาษา Swift ก็มี Higher-order functions ให้ใช้เหมือนกับภาษาอื่นๆ อย่างเช่น map filter อะไรพวกนี้ เรามาดูกันหน่อยว่าเราจะสามารถใช้พวกนี้ใน Swift ได้อย่างไรบ้าง

Map

Map function ใช้สำหรับแปลงข้อมูลใน array จากรูปแบบนึงไปสู่อีกรูปแบบนึง โดยเมื่อแปลงเสร็จแล้ว จะสร้างเป็น collection ใหม่

ตัวอย่างเช่น ถ้าอยากจะแปลงข้อมูลใน array string ชุดนี้ให้เป็น uppercase ทั้งหมด ก็จะเป็น

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let uppercase = cast.map { val in
    val.uppercased()
}
 
// uppercase: ["VIVIEN", "MARLON", "KIM", "KARL"]

หรือจะเอามานับจำนวน character ใน string ก็ทำได้เหมือนกัน

let count = cast.map { val in
    val.count
}
 
// count: [6, 6, 3, 4]

CompactMap

compactMap function จะคล้ายกับ map แต่เราสามารถการกรองข้อมูลที่เป็น nil ออกไปได้

อย่างเช่นในตัวอย่างนี้ เราสามารถกรองข้อมูลที่สามารถแปลงไปเป็นตัวเลขได้อย่างเดียวได้

let numbers = ["1", "2", "three", "///4///", "5"]
let compactMapped = numbers.compactMap { val in Int(val) }
 
// compactMapped: [1, 2, 5]

FlatMap

flatMap function ใช้เพื่อรวม collection ของ collections ให้เป็นระดับเดียว ให้นึกถึง nested array หรือ array ที่มีการซ้อนกันหลายๆ ชั้น สามารถนำ flatMap มาช่วยได้

let nestedArrays = [[1, 2], [3, 4], [5, 6]]
let flattenedArray = nestedArrays.flatMap { $0 }
// flattenedArray: [1, 2, 3, 4, 5, 6]

Sort

sort function ใช้สำหรับเรียงข้อมูลใน array

let unsortedNumbers = [3, 1, 4, 1, 5, 9, 2, 6]
let sortedNumbers = unsortedNumbers.sorted()
// sortedNumbers: [1, 1, 2, 3, 4, 5, 6, 9]

Filter

filter function ใช้สำหรับกรองข้อมูลตามเงื่อนไขที่เราต้องการ

อย่างในตัวอย่างนี้ จะกรองตัวเลขที่เป็นเลขคู่

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let evenNumbers = numbers.filter { val in
    val % 2 == 0
}
// evenNumbers: [2, 4, 6, 8, 10]

Reduce

reduce function ใช้สำหรับรวมค่าใน collection ให้เป็นค่าค่าเดียว วิธีการคร่าวคือเราต้องกำหนดค่าเริ่มต้นก่อน จากนั้นใน body ของ closures ก็ทำการรวมค่าก่อนหน้ากับค่าปัจจุบันเข้าด้วยกัน

ในตัวอย่างนี้จะรวมค่าใน array

let numbers = [1, 2, 3, 4, 5]
let sum = numbers.reduce(0) { prev, cur in
    prev + cur
}
// sum: 15

Reference

Tags:

Swift