Skip to content

Latest commit

 

History

History
125 lines (78 loc) · 3 KB

File metadata and controls

125 lines (78 loc) · 3 KB

Basics | Arrays | Colors | Date and Time | Dictionaries | Sets | Sorting | Strings | Functional Swift

Functional Swift

map

[1,2,3].map {$0 * 2}

let row = "id first last"
let csv = String(row.map {$0 == " " ? "," : $0}) // replace all occurrences
let xs:[Int] = stride(from: -100, to: 110, by: 10).map {$0} // [-100, -90, -80, ..., 100]

map(_:)

filter

let evens = [1,2,3,4,5,6,7,8,9].filter {$0 % 2 == 0} // isEven
["5", "a", "6","b"].filter {($0 as Character).isNumber}

filter(_:)

forEach

[pronounView, answerWellView, answerConjugationView].forEach (view.addSubview)

forEach(_:)

reduce

let sum = [1,2,3].reduce(0, +)
let product = [1,2,3].reduce(1, *)

reduce(::) | reduce(into:_:)

flatMap, compactMap

flatMap has been deprecated in Swift, use compactMap.

["55", "a", "6","b"].compactMap {Int($0)}

compactMap(_:)

take

[1,2,3,4,5,6,7,8,9].prefix(3)

If you wanted to have your own take extension on Array, you could add something like the following:

extension Array {
    func take(_ n: Int) -> ArraySlice<Element> {
        self[0..<n]
    }
}

let ar0 = [1,2,3].take(2)
["a","b","c"].take(2)

prefix(_:)

takeWhile

[1,2,3,4,-5,6,7,8,9].prefix(while: {$0 > 0} )

prefix(while:)

drop/dropWhile

let xs = [1,2,3] + [4,5,6]
let test = (0...3).drop { $0 > 1 } //dropWhile

xs.drop { $0 <= 3 }
//[1,2,3,4,5,6].drop(while: 2)
[1,2,3,4,5,6].dropFirst(3)
[1,2,3,4,5,6].dropFirst() // defaults to 1

[1,2,3,4,5,6].dropLast() // defaults to 1

drop(while:) | dropFirst(_:) | dropLast(_:)

zip

let companies = ["Apple", "Google", "Microsoft"]
let tickers = ["AAPL", "GOOGL","MSFT"]

for (ticker, company) in zip(tickers, companies) {
    print("\(ticker),\(company)")
}

Combining

[1,2,3,4,5,6,7,8,9].filter {$0 % 2 == 0}.map {$0 * 2}.reduce(0, +)
["550", "a", "6", "b", "42", "99", "100"].compactMap {Int($0)}.filter {$0 < 100}