• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Swift中Array的常见遍历操作

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

max方法

利用max方法,可直接遍历出数组中最大值和最小值

var arr = [1, 2, 3, 4]
//// 返回数组中的最大值 和 最小值
//@inlinable public func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> Element?
// 根据返回值true和false返回数组中的最大值和最小值,是一个可选值
var maxElement = arr.max { (temp1, temp2) -> Bool in
    return temp1 < temp2
}

map方法

map方法可遍历整个数组,并对数组个每个元素进行操作,返回处理后的数组

/// 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]
var arr3 = arr.map { (temp) -> Int in
    return temp * 2
}
print(arr3)
//[2, 4, 6, 8]

filter方法

filter方法可遍历整个数组,并依据设置的条件,对数组筛选并返回新的数组

// 根据条件进行过滤
var arr4 = arr.filter { (temp) -> Bool in
    return temp % 2 == 0
}
print(arr4)
// [2, 4]

reduce方法

reduce设置初始参数,根据传入的闭包操作,返回结果。例如相乘或者相加

/// Returns the result of combining the elements of the sequence using the
/// given closure.
// @inlinable public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
var arr5 = arr.reduce(5) { (result, temp) -> Int in
    // 5 * 1 * 2 * 3 * 4
    return result * temp
}
//简便写法 var arr6 = arr.reduce(5, *)

print(arr5)
// 120

map和flatMap区别

// @inlinable public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
var arr7 = arr.map { Array.init(repeating: $0, count: $0) }
print(arr7)

/// Returns an array containing the concatenated results of calling the
/// given transformation with each element of this sequence.
/// In fact, `s.flatMap(transform)`  is equivalent to
/// `Array(s.map(transform).joined())`.
//@inlinable public func flatMap<SegmentOfResult>(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence
var arr8 = arr.flatMap { Array.init(repeating: $0, count: $0) }
print(arr8)
//[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
//[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

两者相比较,正如文档注释一下flatMap会拼接成一个数组

map和compactMap区别

var stringArr = ["123", "test", "haha", "-234"]
var arr2 = stringArr.map { Int($0) }
print(arr2)
/// Returns an array containing the non-`nil` results of calling the given
/// transformation with each element of this sequence.
var arr3 = stringArr.compactMap { Int($0) }
print(arr3)
//[Optional(123), nil, nil, Optional(-234)]
//[123, -234]

map会完成所传入的闭包操作,若是失败会赋值为空,成功会返回一个可选值

compactMap根据闭包的操作,若是失败则被移除,返回的解包后的值

Array中lazy方法

let result = arr.map { (temp) -> Int in
    print("map \(temp)")
    return temp * 2
}

print("begin--")
print("test", result[0])
print("test", result[1])
print("test", result[2])
print("end")

数组的遍历未使用lazy时候,打印结果如下:

map 1
map 2
map 3
map 4
begin--
test 2
test 4
test 6
end

会先按照顺序执行,执行完map遍历,再执行下面的打印

而对于利用lazy遍历来说,代码如下:

let result = arr.lazy.map { (temp) -> Int in
    print("map \(temp)")
    return temp * 2
}

print("begin--")
print("test", result[0])
print("test", result[1])
print("test", result[2])
print("end")

打印结果如下:

begin--
map 1
test 2
map 2
test 4
map 3
test 6
end

会发现数组里面的打印会在该数组的元素被使用的时候才会调用,这个方法适用于当数组元素的数量比较大时候


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap