Skip to content

Instantly share code, notes, and snippets.

View saoudrizwan's full-sized avatar

Saoud Rizwan saoudrizwan

View GitHub Profile
let evenNumbers = [1, 2, 3, 4, 5].filter { $0 % 2 == 0 }
/// Returns an array containing, in order, the elements of the sequence
/// that satisfy the given predicate.
/// - Parameter shouldInclude: A closure that takes an element of the
/// sequence as its argument and returns a Boolean value indicating
/// whether the element should be included in the returned array.
/// - Returns: An array of the elements that `includeElement` allowed.
public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]
let numbers = [1, 2, 3, 4, 5].map { $0 * 2 }
print(numbers) // [2, 4, 6, 8, 10]
let arrayWithNoNils = [1, 2, 3, nil].flatMap { $0 }
print(arrayWithNoNils) // [1, 2, 3]
let arrayWithNoOptionals = ["1", "two", "3"].flatMap { Int($0) }
print(arrayWithNoOptionals) // [1, 3]
/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
/// - Parameter transform: A mapping closure. `transform` accepts an
/// element of this sequence as its parameter and returns a transformed
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
func doSomething(closure: () throws -> String) rethrows -> String {
return try closure()
}
extension Int {
func doMath(_ transform: ((Int) -> (Int)) ) -> (Int) {
return transform(self)
}
}
let doubled = 5.doMath { (number) -> (Int) in
return number * 2
}
print(doubled) // 10
let array = [1, 2, 3].map { $0 * 2 }
let newArray = array.flatMap { String($0) }