popeyelau / wiki

📒Wiki for many useful notes, source, commands and snippets.
3 stars 0 forks source link

Higher Order Function in Swift #10

Open popeyelau opened 5 years ago

popeyelau commented 5 years ago
//map
let strings = (1...5).map(String.init) //same as .map { String($0) }
print(strings) //["1", "2", "3", "4", "5"]

//filter
let names = ["Popeye", "Oyl", "Edison"].filter { $0.count > 3 }
print(names) //["Popeye", "Edison"]

//compactMap
let numbers = ["1", "2", "hello"].compactMap { Int($0) }
print(numbers) //[1, 2]

//flatMap
let flat = [[1,2,3], [4,5,6]].flatMap { $0 }
print(flat) //[1, 2, 3, 4, 5, 6]

//sorted
let sorted = flat.sorted(by: >)
print(sorted) //[6, 5, 4, 3, 2, 1]

//reduce
let sayHello =  ["h", "e", "l", "l", "o"].reduce("Say ", +)
print(sayHello) // Say hello

let sum = [1,2,3,4,5].reduce(0, +)
print(sum) //15

//allSatisfy
print("allSatisfy: ", [1,2,3,4,5].allSatisfy { $0 > 3}) //allSatisfy:  false
popeyelau commented 5 years ago
//Dictionary
let citys = ["Shanghai": 200, "Shenzhen": 300, "Guangzhou": 400]
print(citys.filter { $0.value > 200}) //["Shenzhen": 300, "Guangzhou": 400]
print(citys.mapValues { $0 * 2 }) //["Shanghai": 400, "Shenzhen": 600, "Guangzhou": 800]

//grouping
let grouped = Dictionary(grouping: citys.keys) { $0.first!}
print(grouped) //["S": ["Shanghai", "Shenzhen"], "G": ["Guangzhou"]]

// instead of citys["Hongkong"] ?? 500
let value = citys["Hongkong", default: 500]
print(value) //500

//One-sided ranges
let nums = [0,1,2,3,4,5]
let bigParts = nums[..<3] //0, 1, 2
let smallParts = nums[3...] //3, 4, 5
print(bigParts)
print(smallParts)

//random
let randomInt = Int.random(in: 1..<10)
print(randomInt)

//Boolean toggle
var isMarked = false
isMarked.toggle() //true