Swift 3:如何使用for循环来循环数组

时间:2017-02-01 08:37:44

标签: ios arrays swift3

方案

假设我有array = ["a", "b", "c", "d"]

我有一个button功能,允许我打印此数组中的数据。我使用for循环遍历数组。

但是在第四次点击后打印最后一个数组元素(index[3])之后,我希望它在第五次点击时从头开始打印(index[0])。

非常感谢任何帮助!

谢谢

5 个答案:

答案 0 :(得分:3)

保持点击计数var(初始化为0)并在点击按钮时使用以下内容:

let valToPrint = yourArray[clickCount % yourArray.count]
clickCount += 1

print("Current value = \(valToPrint)")

%(modulos)运算符将循环clickCount到所需范围。

答案 1 :(得分:3)

为此你需要简单地维护数组对象的当前元素的索引。

var currentIndex = 0

@IBAction func buttonClick(_ sender: UIButton) {
    print(array[currentIndex])
    currentIndex += 1
    if currentIndex == array.count { 
        currentIndex = 0 
    }
}

答案 2 :(得分:1)

你可以写

.done(function (data, textStatus, jqXHR) //success callback
{
    $('#optionsId').val(data.optionsId); // updates the hidden input
    $('#PrintAddress').prop('checked', data.PrintAddress); // update the checkbox
    ....
}

enter image description here

答案 3 :(得分:0)

在按钮点击下面写下代码

@IBAction func myButton(_ sender: UIButton) {

    if sender.tag > array.count{
        sender.tag = 0
    }

    print("array[\(sender.tag)] = \(array[sender.tag])")
    sender.tag += 1

}

答案 4 :(得分:0)

对于它的技术乐趣:另一种选择是定义一个循环遍历数组元素的序列。

给定一个不可变数组:

class Foo {
    private let array: [String]

    private lazy var cyclingSequenceOverArray: 
        UnfoldSequence<String, Int> = sequence(state: -1) {
        (state: inout Int) -> String? in
        guard !self.array.isEmpty else { return nil }
        return self.array[(state = (state + 1) % self.array.count, state).1]
    }

    init(_ array: [String]) {
        self.array = array
    }

    func printNext() {
        if let next = cyclingSequenceOverArray.next() {
            print(next)
        }
    }
}

let foo = Foo(["a", "b", "c", "d"])

foo.printNext() // a
foo.printNext() // b
foo.printNext() // c
foo.printNext() // d
foo.printNext() // a
foo.printNext() // b

如果让数组变为可变(var)并且它变为空:对序列的next()方法(如上所述)的调用将终止序列。即,即使要重新填充数组,随后对next()的调用仍会产生nil。在这种情况下,您可以让序列为无限(永不终止),只需返回一个默认值,以防数组为nil

class Foo {
    var array: [String]

    private lazy var cyclingSequenceOverArray: 
        UnfoldSequence<String, Int> = sequence(state: -1) {
        (state: inout Int) -> String in
        guard !self.array.isEmpty else { return (state = -1, "Empty!").1 }
        return self.array[(state = (state + 1) % self.array.count, state).1]
    }

    init(_ array: [String]) {
        self.array = array
    }

    func printNext() {
        if let next = cyclingSequenceOverArray.next() {
            print(next)
        }
    }
}

使用示例:

let foo = Foo(["a", "b", "c", "d"])

foo.printNext() // a
foo.printNext() // b
foo.printNext() // c

foo.array = []

foo.printNext() // Empty!
foo.printNext() // Empty!

foo.array = ["a", "b", "c", "d"]

foo.printNext() // a
foo.printNext() // b
foo.array[2] = "C"
foo.printNext() // C

foo.array = ["1", "2", "3"]

foo.printNext() // 1
相关问题