欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Swift map和filter函數(shù)原型基礎(chǔ)示例

 更新時(shí)間:2023年07月07日 10:41:27   作者:大劉  
這篇文章主要為大家介紹了Swift map和filter函數(shù)原型基礎(chǔ)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

map函數(shù)原型

/// 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 = cast.map { $0.lowercased() }
///     // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
///     let letterCounts = cast.map { $0.count }
///     // '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 = cast.map {
    $0.lowercased()
}
print(lowercaseNames) // ["vivien", "marlon", "kim", "karl"]
let arrayString = ["Ann", "Bob", "Tom", "Lily", "HanMeiMei", "Jerry"]
// 計(jì)算每個(gè)元素的個(gè)數(shù),生成個(gè)數(shù)數(shù)組
let arrayCount = arrayString.map { (str) -> Int in
    return str.count
}
print("arrayCount: \(arrayCount)")
// arrayCount: [3, 3, 3, 4, 9, 5]

filter函數(shù)原型

// @inlinable public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]
let array = [-5, 4, -3, 1, 2]
var resultArray = array.filter { (item) -> Bool in
    return item > 0
}
print(resultArray) // [4, 1, 2]
// 語法糖寫法
resultArray = array.filter {
    $0 > 0
}
print(resultArray) // [4, 1, 2]

以上就是Swift map和filter函數(shù)原型基礎(chǔ)示例的詳細(xì)內(nèi)容,更多關(guān)于Swift map filter函數(shù)原型的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論