Swift map和filter函數(shù)原型基礎(chǔ)示例
更新時間:2023年07月07日 10:41:27 作者:大劉
這篇文章主要為大家介紹了Swift map和filter函數(shù)原型基礎(chǔ)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
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ù)原型基礎(chǔ)示例的詳細內(nèi)容,更多關(guān)于Swift map filter函數(shù)原型的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
swift 3.0中實現(xiàn)字符串截取、比較的方法示例
時,為了使用現(xiàn)有的字符串生成一個新的字符串,我們可以使用截取字符串的方法實現(xiàn)。下面這篇文章主要給大家介紹了關(guān)于swift 3.0中實現(xiàn)字符串截取的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒。2017-10-10Swift調(diào)用Objective-C編寫的API實例
這篇文章主要介紹了Swift調(diào)用Objective-C編寫的API實例,介紹的比較全面和詳細,對Objective-C代碼的重復利用有極大好處,的朋友可以參考下2014-07-07iPhone與iWatch連接、控制、數(shù)據(jù)傳遞(Swift)的方法
這篇文章主要介紹了iPhone與iWatch連接、控制、數(shù)據(jù)傳遞(Swift)的方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-03-03SwiftUI開發(fā)總結(jié)combine原理簡單示例詳解
這篇文章主要為大家介紹了SwiftUI開發(fā)總結(jié)combine原理簡單示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02深入探究Swift枚舉關(guān)聯(lián)值的內(nèi)存
這篇文章主要給大家介紹了關(guān)于Swift枚舉關(guān)聯(lián)值的內(nèi)存的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者使用Swift具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2020-08-08Swift 中如何使用 Option Pattern 改善可選項的 API 設計
這篇文章主要介紹了Swift 中如何使用 Option Pattern 改善可選項的 API 設計,幫助大家更好的進行ios開發(fā),感興趣的朋友可以了解下2020-10-10