[英]Swift iOS. Program crashes when i try to mutate an array of buttons
I have about 20 buttons linked to allKeys
. 我有大约20个链接到
allKeys
按钮。 I want the turnRed button to change the color of their text to red. 我希望turnRed按钮将其文本的颜色更改为红色。 I tried the following code:
我尝试了以下代码:
@IBOutlet var allKeys: [UIButton]!
@IBAction func turnRed(sender: UIButton) {
var i = allKeys.count
repeat {
allKeys[i].setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
i -= 1
} while i != -1
}
When I press the turnRed button, my program crashes and xcode jumps to the appDelegate file and highlights the AppDelegate class with the error Thread1: signal SIGABRT. 当我按下turnRed按钮时,程序崩溃,xcode跳至appDelegate文件,并突出显示AppDelegate类,错误为Thread1:signal SIGABRT。
The console says "Terminating app due to uncaught exception 'NSRangeException Reason: NSArrayI objectAtIndex 控制台显示“由于未捕获的异常'NSRangeException而终止应用程序,原因:NSArrayI objectAtIndex
The issue here is that you are setting the variable i
to allKeys.count
, but since arrays in swift start with zero, the twentieth element should actually be allKeys[19]
. 这里的问题是,您将变量
i
设置为allKeys.count
,但是由于swift中的数组从零开始,因此第二十个元素实际上应该是allKeys[19]
。 Thus, when the loop is at i = 20
, it tries to access allKeys[20]
, which crashes the app. 因此,当循环在
i = 20
,它将尝试访问allKeys[20]
,这会使应用程序崩溃。
One way to solve this is to set i
to allKeys.count - 1
instead, but a better way would be to use a for-in
loop instead of repeat
. 解决此问题的一种方法是将
i
设置为allKeys.count - 1
,但是更好的方法是使用for-in
循环而不是repeat
。
for key in allKeys {
key.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
}
There are multiple ways to loop in Swift, and you should use the options to your advantage. 在Swift中有多种循环方法,您应该使用这些选项以发挥自己的优势。 You can find Apple's documentation for Control Flow here .
您可以在此处找到Apple的Control Flow文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.