Basics | Arrays | Colors | Date and Time | Dictionaries | Sets | Sorting | Strings | Functional Swift
[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]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}[pronounView, answerWellView, answerConjugationView].forEach (view.addSubview)let sum = [1,2,3].reduce(0, +)
let product = [1,2,3].reduce(1, *)flatMap has been deprecated in Swift, use compactMap.
["55", "a", "6","b"].compactMap {Int($0)}[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)[1,2,3,4,-5,6,7,8,9].prefix(while: {$0 > 0} )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 1drop(while:) | dropFirst(_:) | dropLast(_:)
let companies = ["Apple", "Google", "Microsoft"]
let tickers = ["AAPL", "GOOGL","MSFT"]
for (ticker, company) in zip(tickers, companies) {
print("\(ticker),\(company)")
}[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}