SoFunction
Updated on 2025-04-11

Basic examples of Swift map and filter function prototypes

Map function prototype

/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
///
/// In this example, `map` is used first to convert the names in the array
/// to lowercase strings and then to count their characters.
///
///     let cast = ["Vivien", "Marlon", "Kim", "Karl"]
///     let lowercaseNames =  { $() }
///     // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
///     let letterCounts =  { $ }
///     // 'letterCounts' == [6, 6, 3, 4]
///
/// - 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.
@inlinable public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames =  {
    $()
}
print(lowercaseNames) // ["vivien", "marlon", "kim", "karl"]
let arrayString = ["Ann", "Bob", "Tom", "Lily", "HanMeiMei", "Jerry"]
// Calculate the number of each element and generate an array of numberslet arrayCount =  { (str) -&gt; Int in
    return 
}
print("arrayCount: \(arrayCount)")
// arrayCount: [3, 3, 3, 4, 9, 5]

filter function prototype

// @inlinable public func filter(_ isIncluded: (Element) throws -&gt; Bool) rethrows -&gt; [Element]
let array = [-5, 4, -3, 1, 2]
var resultArray =  { (item) -&gt; Bool in
    return item &gt; 0
}
print(resultArray) // [4, 1, 2]
// Syntax sugar writingresultArray =  {
    $0 &gt; 0
}
print(resultArray) // [4, 1, 2]

The above is the detailed content of the basic examples of Swift map and filter function prototypes. For more information about Swift map filter function prototypes, please follow my other related articles!