Swift for循环:用于索引,数组中的元素?
本文翻译自:Swift for loop: for index, element in array?
Is there a function that I can use to iterate over an array and have both index and element, like python's enumerate? 有没有可以用来遍历数组并具有索引和元素的函数,例如python的enumerate?
for index, element in enumerate(list):...
#1楼
参考:https://stackoom.com/question/1cotB/Swift-for循环-用于索引-数组中的元素
#2楼
Yes. 是。 As of Swift 3.0, if you need the index for each element along with its value, you can use the enumerated()
method to iterate over the array. 从Swift 3.0开始,如果需要每个元素的索引及其值,则可以使用enumerated()
方法遍历数组。 It returns a sequence of pairs composed of the index and the value for each item in the array. 它返回由索引和数组中每个项目的值组成的对对的序列。 For example: 例如:
for (index, element) in list.enumerated() {print("Item \(index): \(element)")
}
Before Swift 3.0 and after Swift 2.0, the function was called enumerate()
: 在Swift 3.0之前和Swift 2.0之后,该函数称为enumerate()
:
for (index, element) in list.enumerate() {print("Item \(index): \(element)")
}
Prior to Swift 2.0, enumerate
was a global function. 在Swift 2.0之前, enumerate
是一个全局函数。
for (index, element) in enumerate(list) {println("Item \(index): \(element)")
}
#3楼
I found this answer while looking for a way to do that with a Dictionary , and it turns out it's quite easy to adapt it, just pass a tuple for the element. 我在寻找使用Dictionary做到这一点的方法时找到了这个答案,事实证明,调整它非常容易,只需为元素传递一个元组即可。
// Swift 2var list = ["a": 1, "b": 2]for (index, (letter, value)) in list.enumerate() {print("Item \(index): \(letter) \(value)")
}
#4楼
Starting with Swift 2, the enumerate function needs to be called on the collection like so: 从Swift 2开始,需要在集合上调用枚举函数,如下所示:
for (index, element) in list.enumerate() {print("Item \(index): \(element)")
}
#5楼
Swift 5 provides a method called enumerated()
for Array
. Swift 5为Array
提供了一种称为enumerated()
的方法。 enumerated()
has the following declaration: enumerated()
具有以下声明:
func enumerated() -> EnumeratedSequence<Array<Element>>
Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence. 返回一个成对的序列(n,x),其中n代表一个从零开始的连续整数,x代表该序列的一个元素。
In the simplest cases, you may use enumerated()
with a for loop. 在最简单的情况下,可以将enumerated()
与for循环一起使用。 For example: 例如:
let list = ["Car", "Bike", "Plane", "Boat"]
for (index, element) in list.enumerated() {print(index, ":", element)
}/*
prints:
0 : Car
1 : Bike
2 : Plane
3 : Boat
*/
Note however that you're not limited to use enumerated()
with a for loop. 但是请注意,您不限于将enumerated()
与for循环一起使用。 In fact, if you plan to use enumerated()
with a for loop for something similar to the following code, you're doing it wrong: 实际上,如果您打算将enumerated()
与for循环一起使用,类似于以下代码,则您做错了:
let list = [Int](1...5)
var arrayOfTuples = [(Int, Int)]()for (index, element) in list.enumerated() {arrayOfTuples += [(index, element)]
}print(arrayOfTuples) // prints [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
A swiftier way to do this is: 一个更快的方法是:
let list = [Int](1...5)
let arrayOfTuples = Array(list.enumerated())
print(arrayOfTuples) // prints [(offset: 0, element: 1), (offset: 1, element: 2), (offset: 2, element: 3), (offset: 3, element: 4), (offset: 4, element: 5)]
As an alternative, you may also use enumerated()
with map
: 另外,您也可以将enumerated()
与map
:
let list = [Int](1...5)
let arrayOfDictionaries = list.enumerated().map { (a, b) in return [a : b] }
print(arrayOfDictionaries) // prints [[0: 1], [1: 2], [2: 3], [3: 4], [4: 5]]
Moreover, although it has some limitations , forEach
can be a good replacement to a for loop: 而且,尽管它有一些局限性 ,但是forEach
可以很好地替代for循环:
let list = [Int](1...5)
list.reversed().enumerated().forEach { print($0, ":", $1) }/*
prints:
0 : 5
1 : 4
2 : 3
3 : 2
4 : 1
*/
By using enumerated()
and makeIterator()
, you can even iterate manually on your Array
. 通过使用enumerated()
和makeIterator()
,您甚至可以在Array
上手动进行迭代。 For example: 例如:
import UIKit
import PlaygroundSupportclass ViewController: UIViewController {var generator = ["Car", "Bike", "Plane", "Boat"].enumerated().makeIterator()override func viewDidLoad() {super.viewDidLoad()let button = UIButton(type: .system)button.setTitle("Tap", for: .normal)button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)button.addTarget(self, action: #selector(iterate(_:)), for: .touchUpInside)view.addSubview(button)}@objc func iterate(_ sender: UIButton) {let tuple = generator.next()print(String(describing: tuple))}}PlaygroundPage.current.liveView = ViewController()/*Optional((offset: 0, element: "Car"))Optional((offset: 1, element: "Bike"))Optional((offset: 2, element: "Plane"))Optional((offset: 3, element: "Boat"))nilnilnil*/
#6楼
This is the Formula of loop of Enumeration: 这是枚举循环的公式:
for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}
for more detail you can check Here . 有关更多详细信息,请单击此处 。
Swift for循环:用于索引,数组中的元素?相关推荐
- 利用for循环把遍历数组中的元素依次获取出来 数组笔记及基本知识点
利用for循环把遍历数组中的元素依次获取出来 数组索引号从0开始 所以i必须从0开始 i<6 <script>var arr = ['blue', 2, true, 4, 5, 6 ...
- 一题多解——求数组中每个元素出现的次数
好久没更新博客了,写博客分享是个好习惯,发现坚持是比较难得的一件事情. 2021年第一更,就写一篇比较简单常用的算法入门题吧,主要是利用程序算法思想,求数组中每个元素出现的次数. 先看一下需求描述: ...
- JavaScript 删除数组中指定元素(5种方法)
JavaScript 删除数组中指定元素 在 JavaScript 中,数组是一种常见的数据类型,可以存储多个元素.有时候,我们需要从数组中删除某些特定的元素.本文将介绍如何使用 JavaScript ...
- PHP array_count_values() 函数用于统计数组中所有值出现的次数。
定义和用法 array_count_values() 函数用于统计数组中所有值出现的次数. 本函数返回一个数组,其元素的键名是原数组的值,键值是该值在原数组中出现的次数. 语法 array_count ...
- 循环删除数组中的元素
有一个场景,需要删除满足条件的数据 // 删除小于5的元素 let arr = [1,2,3,4,5,6,7] 代码实现 for (let i = 0, leng = arr.length; i &l ...
- JavaScript中for循环shift()方法删除数组中的元素会被跳过或者只能删除部分
shift()方法用于把数组的第一个元素从其中删除,并返回第一个元素的值. https://blog.csdn.net/qq_36279445/article/details/89497007 ht ...
- 编写类A2, 定义方法find, 实现查找某字符串数组中的元素查找,并返回索引,如果找不到,返回-1
编写类A2, 定义方法find, 实现查找某字符串数组中的元素查找,并返回索引,如果找不到,返回-1 思路: 方法的返回值类型: int 方法名 : find 方法的形参 (String , Stri ...
- 【Linux】Shell脚本中如何使用“循环”遍历“数组”中的元素(包括MySQL的常用指令介绍)
一.背景 实习过程中,今天mentor突然让我拉取一下远端园区数据库中的部分信息,因为包含很多不同园区的数据信息,而且要以园区为单位生成文件来对数据进行存放,因此自然是需要使用shell脚本来自动生成 ...
- Python找出二维数组中某个元素索引,自定义函数
#函数:找出二维数组中某个元素的索引 #功能:返回目标元素在原数组中出现位置的所有索引号 def found(List,AimList):#List:搜索数组,AimList:目标元素print('原 ...
最新文章
- numpy.random.uniform()
- 版本控制 Git RPM打包
- 判别器loss为0_TensorFlow v2.0实现逻辑斯谛回归
- 【渝粤题库】国家开放大学2021春2718动物生理基础题目
- 从DataTable导出Excel,并下载,删除Excel进程。
- hbase 页面访问_HBase
- 八、JQurey总结
- H.264笔记之三——环路内滤波
- python大数据培训好不好
- 【机器学习】第一章 - 机器学习概论 - 周志华机器学习笔记
- python职场应用英语作文_春考关于职场应用的英语作文
- Office Word 2010 2013 插入复选框 方框打勾 对号
- mysql basemapper_BaseMapper和继承
- 电力行业适合学习的开源软件
- 分布式Restful SpringBoot骨架搭建
- Layer Emitter(图层发射器)
- 信息检索(IR)笔记1: 倒排索引(Inverted Index)
- Linux下玩转Dota2
- numpy.max中参数axis的取值问题
- build.gradle 中compileSdkVersion,minSdkVersion,targetSdkVersion,buildToolsVersion的意思
热门文章
- GitHub热门:程序员的架构师封神之路
- Android 事件分发面试
- 2020年总结以及21年规划
- 使用WakeLock将Android应用程序保持后台唤醒
- JAVA层HIDL服务的注册原理-Android10.0 HwBinder通信原理(八)
- Android之Android实现浮层的上下滑动(支持内部添加View)
- Swift使用通知Notification
- (0107)iOS开发之UI实时调试InjectionIII的使用
- Trie树【洛谷P3879】 [TJOI2010]阅读理解
- vue-router 的重定向-redirect