Skip to content

Instantly share code, notes, and snippets.

@maximveksler
Last active February 14, 2017 00:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save maximveksler/2d5b1ee071503a187dc12a12a18e80fc to your computer and use it in GitHub Desktop.
Functional Swift - Examples used in https://gumroad.com/l/natural-swift
import Foundation
let fibonacciNumbers = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
let evenFibonacci = fibonacciNumbers.filter { $0 % 2 == 0 }
let names = ["Michael Jackson", "Taylor Swift", "Michael Caine", "Adele Adkinis", "Michael Jordan"]
let result = names.filter { $0.hasPrefix("Michael") }
let words = ["1989", "Fearless", "Red"]
let input = "My favorite album is Fearless"
let wordsResult = words.filter { input.contains($0) }
// flatMap strips optionality, filter retains it.
let nilWords = ["1989", nil, "Fearless", nil, "Red"]
let nilWordsResult = nilWords.filter { $0 != nil }
type(of: nilWordsResult) // Array<Optional<String>>.Type
import UIKit
let numbers = [[1, 2], [3, 4], [5, 6]]
let joined = Array(numbers.joined())
let albums = ["Fearless", nil, "Speak Now", nil, "Red"]
let result = albums.flatMap { $0 }
let mapResult = albums.map { $0 }
let flatMapResult = albums.flatMap { $0 }
type(of: flatMapResult) // Array<String>.Type
let scores = ["100", "90", "Fish", "85"]
let flatMapScores = scores.flatMap { Int($0) }
let files = (1...10).flatMap { try? String(contentsOfFile: "somefile-\($0).txt") }
let view = UIView()
let labels = view.subviews.flatMap { $0 as? UILabel }
import Foundation
func lengthOf(strings: [String]) -> [Int] {
return strings.map { $0.characters.count }
}
let fruits = ["Apple", "Cheery", "Orange", "Pineapple"]
let upperFruits = fruits.map { $0.uppercased() }
let scores = [100, 80, 85]
let formatted = scores.map { "Your score was \($0)" }
let passOrFail = scores.map { $0 > 85 ? "Pass" : "Fail" }
let position = [50, 60, 40]
let averageResults = position.map { 45...55 ~= $0 ? "Within average" : "Outside average" }
let numbes: [Double] = [4, 9, 25, 36, 49]
let result = numbes.map(sqrt)
import Foundation
let scores = [100, 90, 95]
let sum = scores.reduce(0, +)
let result = scores.reduce("") { $0 + String($1) }
let names = ["Taylor", "Paul", "Adele"]
let count = names.reduce(0) { $0 + $1.characters.count }
let longest = names.reduce("") { $1.characters.count > $0.characters.count ? $1 : $0 }
let longestMax = names.max { $1.characters.count > $0.characters.count }
let numbers = [
[1, 1, 2],
[3, 5, 8],
[13, 21, 34]
]
let flattened: [Int] = numbers.reduce([]) { $0 + $1 }
let flattened2 = numbers.flatMap { $0 }
let flattened3 = Array(numbers.joined())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment