Reputation: 43
func buttonAppearance() {
let buttons = [buttonOneView, buttonTwoView, buttonThreeView, buttonFourView, buttonFiveView, buttonSixView, buttonSevenView, buttonEightView, buttonNineView, buttonTenView, buttonElevenView, buttonTwelveView, previousButtonView, skipButtonView, submitButtonView]
for button in buttons {
button?.layer.cornerRadius = 5.0
button?.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
button?.layer.shadowColor = UIColor.red.cgColor
button?.layer.shadowOpacity = 1.0
}
}
Whenever I comment out the array and any code related to it, the indexing completes and I can run and build just fine. Has anyone else had any issues with this? I researched and saw that it was a bug fixed with Xcode 8.1, but I am all up to date and it's still an issue. I imagine there is a workaround, but that is just dirty.
Upvotes: 2
Views: 580
Reputation: 2461
Try to explicitly declare array type like this:
let buttons: [UIButton] = [buttonOneView, buttonTwoView, buttonThreeView, buttonFourView ... ]
It can be an issue of a Swift type infer system.
Upvotes: 2
Reputation: 154
remove the optional question mark after button. In your array you have as many items as the loop will go through. so you know that "button" will exist in your array as an iterator since you have items in it and you are looping through it.
You say that if you comment out the array the indexing works. But your for loop inside the buttonAppearance() function is DIRECTLY related to the array, so I am not sure what exactly gets indexed when you comment out the array and its related code.
An important question to ask yourself is the data types of items that you placed in the array and whether you need to conform to some protocol if you extended any of your button objects inside of the array. Surely the for loop would work on primitive data types, so if its not an issue with optional (implicit/explicit) handling - then please check your types for the objects you placed inside that array.
Another thing to consider - are you trying to create your buttons array every time the function is called (like changing the appearance theme) or are you trying to reference some global buttons which already exist? In that case - declare the button array outside of the function and just loop through the array inside the function.
If on the other hand - you intend to create the buttons ONLY when the function is called and they dont exist outside of the function globally, you would provide more info about the objects and their type.
It seems to me you have the buttons defined globally outside the function and you are trying to store them all in an array just to loop through them - in which case I would suggest removing the optional "?"
Store the buttons in the array - outside of the function and loop through the array in the function. hope that helps.
Upvotes: 3