12次观看的随机照片 - 致命错误:指数超出范围

时间:2018-03-27 07:19:44

标签: arrays macos loops swift4

我已经Thread 1: Fatal error: Index out of range在NSViews中从数组中循环了我的7张照片。

如何解决?

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)
}

2 个答案:

答案 0 :(得分:1)

这条线似乎错了: view.image = image[i] 图像数组有length = 1

使用view.image = image[0]代替

修改

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)
}

答案 1 :(得分:1)

尝试创建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)))]
    }

}

用法

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

修改

我猜您在以下代码中犯了错误

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

假设photos个对象有10个元素而image个对象的元素少于10个,所以在这种情况下,你会得到这种类型的错误。所以将其更改为以下

for view in arrayOfViews {
    let i = Int(arc4random_uniform(UInt32(image.endIndex)))
    view.image = image[i]
}