有没有办法显示数组中的下一个元素?

时间:2019-05-04 00:43:31

标签: arrays swift

我试图单击一个按钮,并使其打印出数组中的下一个元素。我只希望它在您每次按下按钮时显示下一个元素。

var array = ["one", "two", "three"]

@IBAction func Button(_ sender: Any) {
     print(array[1])    
}

2 个答案:

答案 0 :(得分:0)

进行计数并使用模数:

var array = ["one", "two", "three"]
var counter = 0

@IBAction func Button(_ sender: Any) {
     print(array[counter % array.count])
     counter += 1
}

答案 1 :(得分:0)

另一种方法可以从数组中获取next项以制成Iterator。如果您想用尽所有的值,这很有用。

例如:

var array = ["one", "two", "three"]
var iterator = array.makeIterator()

if let value = iterator.next() {
    print(value)
}
one
if let value = iterator.next() {
    print(value)
}
two
if let value = iterator.next() {
    print(value)
}
three

一旦Iterator超出值,它将返回nil

if let value = iterator.next() {
    print(value)
} else {
    print("out of values")
}
out of values

您还可以在Iterator循环中使用for-in

var array = ["one", "two", "three"]
var iterator = array.makeIterator()

for value in iterator {
    print(value)
}
one
two
three

您可以将其余项目转换为Array

var array = ["one", "two", "three"]

var iterator = array.makeIterator()
let first = iterator.next()!

let rest = Array(iterator)
print(first)
print(rest)
one
["two", "three"]