2017-05-24 73 views
0

假設有一個數組:如何通過按鈕按下數組中的項目?

var items = ["first", "second", "third"] 

每按下一個按鈕,它應該去的下一個項目在數組中的時間。

@IBAction func buttonPressed(_ sender: Any) { 
label.text = currentItem 
     } 

我已經用在循環嘗試,但它只是通過整個數組去一次:

for item in items { 
print(item) 
} 

如何擁有它,所以它只是通過數組中的一個項目開始在一個時間?

+0

有一個整數索引屬性,並在每次按下按鈕後增加它。 – Paulw11

+0

剛剛發佈了一個示例 –

+0

@ Paulw11你會如何去做類似的事情? – SwiftyJD

回答

1

你想要的是維護一個你正在查看的索引的變量。然後,您可以通過它的索引來引用該項目。你會想確保你不會出界。這可以很容易地用模數來完成。

E.g.

var items = ["first", "second", "third"] 
var index = 0 

@IBAction func buttonPressed(_ sender: Any) { 
     label.text = items[index] 
     index = (index + 1) % items.count 
} 

編輯:二進制鴨嘴獸的答案是更好的比我

1

只需跟蹤一個計數器。應該非常簡單。例如:

var items = ["first", "second", "third"] 
var currentIndex: Int = 0 { 
    didSet { 
     currentIndex = currentIndex % items.count 
    } 
} 

@IBAction func buttonPressed(_ sender: Any) { 
    label.text = items[currentIndex] 
    currentIndex += 1 
} 
0

一種方式圍繞保持變量生活在那裏(和搞亂你的代碼)是隻獲取當前對象的索引,並返回下一個還是第一位的,是這樣的:

@IBAction func buttonPressed(_ sender: Any) { 
    guard let text = label.text, let index = items.index(of: text) else { return } 
    label.text = index + 1 < items.count ? items[index + 1] : items[0] 
} 

這使得它讓你的特性是乾淨了一點,它使你的代碼更容易一些跟隨,我想。

+0

雖然這會起作用,但隨着數組變得更大,此方法會變慢。 – Benhamine

+0

確實如此,但我假設他不想用2 mill條目的數組來使用它。這是關於它需要多少才能使其明顯變慢。 –