-1

I've got Thread 1: Fatal error: Index out of range looping my 7 photos from array in NSViews.

How to fix it?

let url = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Desktop/ArrayOfElements")
do {
    let fileURLs = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]).reversed()
    let photos = fileURLs.filter { $0.pathExtension == "jpg" }

    for index in photos {
        let image = [NSImage(data: try Data(contentsOf: index))]

        for view in arrayOfViews {
            let i = Int(arc4random_uniform(UInt32(photos.count-1)))
            view.image = image[i]
        }
    }
} catch {
    print(error)
}
Andy Jazz
  • 49,178
  • 17
  • 136
  • 220
  • I'm a fan of using: https://stackoverflow.com/questions/25329186/safe-bounds-checked-array-lookup-in-swift-through-optional-bindings That way your code will never crash when fetching values from arrays – Vollan Mar 27 '18 at 07:35

2 Answers2

1

It seems that this line is wrong: view.image = image[i] image array has length = 1

Use view.image = image[0] instead

EDIT

let url = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Desktop/ArrayOfElements")
do {
    let fileURLs = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]).reversed()
    let photos = fileURLs.filter { $0.pathExtension == "jpg" }


        for view in arrayOfViews {
            let i = Int(arc4random_uniform(UInt32(photos.count-1)))
            let image = NSImage(data: try Data(contentsOf: photos[i]))
            view.image = image
        }

} catch {
    print(error)
}
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
1

Try to create a category to Collection

extension Collection where Index == Int {

    /**
     Gives a random element of the collection.

     - returns: A random element of the collection.
     */
    func randomElement() -> Iterator.Element? {
        return isEmpty ? nil : self[Int(arc4random_uniform(UInt32(endIndex)))]
    }

}

Usage

let numbers = [1,2,3,4,5,6,7,8,9,10]
let randomNumber = numbers.randomElement()
print(randomNumber!)

Edit:

I guess you are making mistake in the following code

for view in arrayOfViews {
    let i = Int(arc4random_uniform(UInt32(photos.count-1)))
    view.image = image[i]
}

Let's assume photos objects having 10 elements and image object have less than 10 elements, so in such case, you will get this type of error. So change it to the following

for view in arrayOfViews {
    let i = Int(arc4random_uniform(UInt32(image.endIndex)))
    view.image = image[i]
}
Jayachandra A
  • 1,335
  • 1
  • 10
  • 21