从swift数组中删除每个第n个元素 [英] Remove every nth element from swift array

查看:393
本文介绍了从swift数组中删除每个第n个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简便的方法可以从快速数组中删除第n个元素。例如,在下面的数组中:

Is there an easy way to remove every nth element from a swift array. For example, in the array below:

thisArray = [2.0, 4.0, 3.0, 1.0, 4.5, 3.3, 1.2, 3.6, 10.3, 4.4, 2.0, 13.0]

如果 n = 3 并从第一个元素开始计数要返回:

If n = 3 and start count from first element would like to return:

returnThis = [2.0, 4.0, 1.0, 4.5, 1.2, 3.6, 4.4, 2.0]


推荐答案

// swift 4.1:
thisArray.enumerated().compactMap { index, element in index % 3 == 2 ? nil : element }




  • 使用 .enumerated( )附加索引

  • 然后使用 .compactMap 过滤索引2、5处的项目8,...通过返回 nil ,并通过仅返回 element 除去其余的索引。

    • Use .enumerated() to attach the indices
    • Then use .compactMap to filter out items at indices 2, 5, 8, ... by returning nil, and strip the index for the rest by returning just element.
    • (如果您使用的是Swift 4.0或更低版本,请使用 .flatMap 而不是 .compactMap .compactMap 方法是 SE-0187

      (If you are using Swift 4.0 or below, use .flatMap instead of .compactMap. The .compactMap method was introduced in Swift 4.1 by SE-0187)

      (如果您对Swift 2不满意,请使用 .enumerate()代替 .enumerated()。)

      (If you are stuck with Swift 2, use .enumerate() instead of .enumerated().)

      这篇关于从swift数组中删除每个第n个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆