Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- // *********************************
- // ************** MAP **************
- // *********************************
- // Классический вариант
- func lengthOf(strings: [String]) -> [Int] {
- var result = [Int]()
- for string in strings {
- result.append(string.count)
- }
- return result
- }
- // Функциональный вариант
- func flengthOf(strings: [String]) -> [Int] {
- return strings.map { $0.count }
- }
- let fruits = ["Apple", "Cherry", "Orange", "Pineapple"]
- let upperFruits = fruits.map { $0.uppercased() } // ["APPLE", "CHERRY", "ORANGE", "PINEAPPLE"]
- let scores = [100, 80, 85]
- let formatted = scores.map { "Your score was \($0)" } // ["Your score was 100", "Your score was 80", "Your score was 85"]
- let passOfFail = scores.map { $0 > 85 ? "Pass" : "Fail" } // ["Pass", "Fail", "Fail"]
- let position = [50, 60, 40]
- let averageResults = position.map { 45...55 ~= $0 ? "Within average" : "Outside average"} // ["Within average", "Outside average", "Outside average"]
- let numbers: [Double] = [4, 9, 25, 36, 49]
- let result = numbers.map(sqrt) // [2, 3, 5, 6, 7]
- // *********************************
- // *********** FLATMAP *************
- // *********************************
- let numbers = [[1, 2], [3, 4], [5, 6]]
- let joined = Array(numbers.joined()) // [1, 2, 3, 4, 5, 6]
- print(joined)
- let albums: [String?] = ["Fearless", nil, "Speak Now", nil, "Red"]
- let result = albums.map { $0 } // [Optional("Fearless"), nil, Optional("Speak Now"), nil, Optional("Red")]
- let flat_result = albums.flatMap { $0 } // ["Fearless", "Speak Now", "Red"]
- let compact_result = albums.compactMap { $0 } // ["Fearless", "Speak Now", "Red"]
- print(compact_result)
- let scores = ["100", "90", "Fish", "85"]
- let flatMapScores = scores.flatMap { Int($0) } // [100, 90, 85]
- let compactMapScores = scores.flatMap { Int($0) } // [100, 90, 85]
- print(compactMapScores)
- let flatMapFiles = (1...10).flatMap({ try? String(contentsOfFile: "someFile-\($0).txt") }) // []
- let compactMapFiles = (1...10).compactMap({ try? String(contentsOfFile: "someFile-\($0).txt") }) // []
- print(compactMapFiles)
- let view = UIView()
- let flatMaplabels = view.subviews.flatMap({ $0 as? UILabel }) // []
- let compactMaplabels = view.subviews.compactMap({ $0 as? UILabel }) // []
- // *********************************
- // ************ FILTER *************
- // *********************************
- let fibonacciNumbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
- let evenFibonacci = fibonacciNumbers.filter { $0 % 2 == 0 } // [2, 8, 34]
- let names = ["Michael Jackson", "Taylor Swift", "Michael Caine", "Adele Adkins", "Michael Jordan"]
- let result = names.filter({ $0.hasPrefix("Michael") }) // ["Michael Jackson", "Michael Caine", "Michael Jordan"]
- let words = ["1989", "Fearless", "Red"]
- let input = "My favorite album is Fearless"
- let wordsResult = words.filter({ input.contains($0) }) // ["Fearless"]
- let optionalWords: [String?] = ["1989", nil, "Fearless", nil, "Red"]
- let optionalWordsResult = optionalWords.filter({ $0 != nil }) // [Optional("1989"), Optional("Fearless"), Optional("Red")]
- print(optionalWordsResult)
- // *********************************
- // ************ REDUCE *************
- // *********************************
- let scores = [100, 90, 95]
- let sum = scores.reduce(0, +) // 285
- let result = scores.reduce("") { $0 + String($1) } // 1009095
- let names = ["Taylor", "Paul", "Adele"]
- let count = names.reduce(0) { $0 + $1.count } // 15
- let longest = names.reduce("") { $1.count > $0.count ? $1 : $0 } // Taylor
- let anotherLongest = names.max { $1.count > $0.count } // Optional("Taylor")
- let numbers = [
- [1, 1, 2],
- [3, 5, 8],
- [13, 21, 34]
- ]
- let flattened: [Int] = numbers.reduce([]) { $0 + $1 } // [1, 1, 2, 3, 5, 8, 13, 21, 34]
- let flattened2 = numbers.flatMap({ $0 }) // [1, 1, 2, 3, 5, 8, 13, 21, 34]
- let flattened3 = Array(numbers.joined()) // [1, 1, 2, 3, 5, 8, 13, 21, 34]
- // *********************************
- // ********* COMPOSITION ***********
- // *********************************
- let london = (name: "London", continent: "Europe", population: 8_539_000)
- let paris = (name: "Paris", continent: "Europe", population: 2_244_000)
- let lisbon = (name: "Lisbon", continent: "Europe", population: 530_000)
- let rome = (name: "Rome", continent: "Europe", population: 2_627_000)
- let tokyo = (name: "Tokyo", continent: "Asia", population: 13_350_000)
- let cities = [london, paris, lisbon, rome, tokyo]
- let totalPopulation = cities.reduce(0) { $0 + $1.population } // 27290000
- let europePopulation = cities.filter({ $0.continent == "Europe" }).reduce(0) { $0 + $1.population } // 13940000
- let biggestCities = cities.filter({ $0.population > 2_000_000 }).sorted(by: { $0.population > $1.population }).prefix(upTo: 3).map { "\($0.name) is a big city. with a population of \($0.population)" }.joined(separator: "\n")
- /*
- Tokyo is a big city. with a population of 13350000
- London is a big city. with a population of 8539000
- Rome is a big city. with a population of 2627000
- */
- precedencegroup CompositionPrecedence {
- associativity: left
- }
- infix operator >>>: CompositionPrecedence
- func >>> <T, U, V>(lhs: @escaping (T) -> U, rhs: @escaping (U) -> V) -> (T) -> (V) {
- return { rhs(lhs($0)) }
- }
- //func >>> (lhs: @escaping (Int) -> String, rhs: @escaping (String) -> [String]) -> (Int) -> [String] {
- // return { rhs(lhs($0)) }
- //}
- func generateRandomNumber(max: Int) -> Int {
- let number = Int(arc4random_uniform(UInt32(max)))
- print("Using number: \(number)")
- return number
- }
- func calculateFactors(number: Int) -> [Int] {
- return (1...number).filter { number % $0 == 0 }
- }
- func reduceToString(numbers: [Int]) -> String {
- return numbers.reduce("Factors: ") { $0 + String($1) + " " }
- }
- let result = reduceToString(numbers: calculateFactors(number: generateRandomNumber(max: 100)))
- print(result)
- let combined = generateRandomNumber >>> calculateFactors >>> reduceToString
- print(combined(100))
Add Comment
Please, Sign In to add comment