可霓奶奶 發表於 2023-7-7 10:41:27

Swift map和filter函数原型基础示例

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>map函数原型</li><li>filter函数原型</li></ul></div><p class="maodian"></p><h2>map函数原型</h2>
<div class="jb51code"><pre class="brush:cpp;">/// 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' ==
///
/// - 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&lt;T&gt;(_ transform: (Element) throws -&gt; T) rethrows -&gt; </pre></div>
<div class="jb51code"><pre class="brush:cpp;">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"]
// 计算每个元素的个数,生成个数数组
let arrayCount = arrayString.map { (str) -&gt; Int in
    return str.count
}
print("arrayCount: \(arrayCount)")
// arrayCount: </pre></div>
<p class="maodian"></p><h2>filter函数原型</h2>
<div class="jb51code"><pre class="brush:cpp;">// @inlinable public func filter(_ isIncluded: (Element) throws -&gt; Bool) rethrows -&gt;
let array = [-5, 4, -3, 1, 2]
var resultArray = array.filter { (item) -&gt; Bool in
    return item &gt; 0
}
print(resultArray) //
// 语法糖写法
resultArray = array.filter {
    $0 &gt; 0
}
print(resultArray) // </pre></div>
<p>以上就是Swift map和filter函数原型基础示例的详细内容,更多关于Swift map filter函数原型的资料请关注琼殿技术社区其它相关文章!</p>
                           
                            <div class="art_xg">
                              <b>您可能感兴趣的文章:</b><ul><li>Swift 进阶 —— map 和 flatMap的使用</li><li>Swift函数提前返回实例详解</li><li>Swift如何调用Objective-C的可变参数函数详解</li><li>swift 常用高阶函数分享</li><li>C语言中调用Swift函数实例详解</li><li>深入理解swift变量和函数</li><li>详解Swift中的函数及函数闭包使用</li></ul>
                            </div>

                        </div>
                        <!--endmain-->
頁: [1]
查看完整版本: Swift map和filter函数原型基础示例