Swift map和filter函數(shù)原型基礎示例
更新時間:2023年07月07日 10:41:27 作者:大劉
這篇文章主要為大家介紹了Swift map和filter函數(shù)原型基礎示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
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"]
// 計算每個元素的個數(shù),生成個數(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ù)原型基礎示例的詳細內容,更多關于Swift map filter函數(shù)原型的資料請關注腳本之家其它相關文章!
相關文章
Swift自定義iOS中的TabBarController并為其添加動畫
這篇文章主要介紹了Swift自定義iOS中的TabBarController并為其添加動畫的方法,即自定義TabBarController中的的TabBar并為自定義的TabBar增加動畫效果,需要的朋友可以參考下2016-04-04
swift4 使用DrawerController實現(xiàn)側滑菜單功能的示例代碼
這篇文章主要介紹了swift4 使用DrawerController實現(xiàn)側滑功能的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06
Swift實現(xiàn)JSON轉Model的方法及HandyJSON使用講解
這篇文章給大家介紹了Swift實現(xiàn)JSON轉Model的方法及HandyJSON使用講解,非常不錯,具有參考借鑒價值,需要的朋友參考下吧2017-07-07

