Reputation: 157
I have been getting the error of index beyond bounds.
I have been dealing with ZLSwipeableView Swift Version.
The code
import UIKit
class SwipeableViewController: UIViewController {
var swipeAbleView : ZLSwipeableView!
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
swipeAbleView.nextView = {
return self.nextCardView()
}
}
// This is the colors array
var colors : NSArray = NSArray(array: [UIColor.orangeColor() , UIColor.blueColor() , UIColor.greenColor() , UIColor.blackColor() , UIColor.brownColor() , UIColor.magentaColor()])
var v : UIView!
var cardsCount = 6
var cardsIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = UIColor.whiteColor()
view.clipsToBounds = true
swipeAbleView = ZLSwipeableView()
swipeAbleView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
self.swipeAbleView.alpha = 0.0
UIView.animateWithDuration (0.25, delay: 0.35, options: UIViewAnimationOptions.CurveLinear ,animations: {
self.swipeAbleView.alpha = 1.0
}, completion:nil)
self.view.addSubview(swipeAbleView)
self.swipeAbleView.discardViews()
self.swipeAbleView.loadViews()
}
func nextCardView() -> UIView {
if cardsIndex < cardsCount {
cardsIndex += 1
}
let cardView = CardView(frame: self.swipeAbleView.bounds)
// The error occurs here and the app crashes
cardView.backgroundColor = colors[cardsIndex] as? UIColor
return cardView
}
}
The error occurs when I define the color for the cardView.
The application crashes I get the error.
Upvotes: 0
Views: 306
Reputation: 2085
The clear answer here is to write an extension for integer that clamps the value
extension Int {
func clamp(minRange: Int, maxRange: Int) {
self = min(maxRange, self)
self = max(minRange, self)
}
}
then do this
cardsIndex.clamp(0, cardsIndex + 1)
Upvotes: 0
Reputation: 130082
if cardsIndex < cardsCount {
cardsIndex += 1
}
This condition does not prevent you from going over the bounds, the correct condition would be:
if cardsIndex + 1 < cardsCount {
cardsIndex += 1
}
Although I would consider very strange to change data from viewDidLayoutSubviews
.
Upvotes: 3