选项问题

发布于 2025-02-02 12:13:40 字数 648 浏览 3 评论 0原文

我开始从书籍和YouTube的教程中自己学习swift。当我尝试重复视频时,我得到了错误

“线程1:致命错误:未包装可选值时出乎意料的发现”

in Cyce 中的

问题是什么?

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var collectionViwe: UICollectionView!
    
    var imagesUIImages = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionViwe.dataSource = self
        collectionViwe.delegate = self
        
        for i in 0...7 {
            let image = UIImage(named: "image \(i)")! 
            imagesUIImages.append(image)
        }
    }
}

I started learning Swift on my own from books and a tutorial from YouTube. And when I tried to repeat over the video, I got the error

"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"`

In the cycle for I in

What is the problem here?

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var collectionViwe: UICollectionView!
    
    var imagesUIImages = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionViwe.dataSource = self
        collectionViwe.delegate = self
        
        for i in 0...7 {
            let image = UIImage(named: "image \(i)")! 
            imagesUIImages.append(image)
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

两仪 2025-02-09 12:13:40

正如Macusert所建议的那样,您可能有7张图像而不是8张。我想补充说,首先解开可选的是明智的,并且是一个很好的做法,如果您有一个值,那么它将添加到列表中图像。

因此,代码是

for i in 0..<7 {
    if let image = UIImage(named: "image \(i)") {
        imagesUIImages.append(image)
    }
}

As MacUserT suggests, you probably have 7 images instead of 8. I would like to add to his answer that it would be wise and a good practice to unwrap the optional first and if you have a value then it will be added to the list of images.

So the code would be,

for i in 0..<7 {
    if let image = UIImage(named: "image \(i)") {
        imagesUIImages.append(image)
    }
}
护你周全 2025-02-09 12:13:40

您可能只有七个图像,而不是八张图像,但是您可以算出八张图像。范围0 ... 7计数到7,包括七个。如果您只有七个图像,则应计数为6,例如0 ..&lt; 7或0 ... 6。

如果您确实只有七个图像,则不存在图像“ Image 7”,并且由于您正在强迫使用它!,您的应用程序会崩溃。

请尝试:

for i in 0..<7 {
    let image = UIImage(named: "image \(i)")! 
    imagesUIImages.append(image)
}

You probably have only seven images and not eight, but you count to eight. The range 0...7 counts to seven, including seven. If you only have seven images, you should count to six, for instance 0..<7 or 0...6.

If you indeed only have seven images, then the image "image 7" doesn't exist and, since you are force unwrapping it with an !, your app crashes.

Please, try:

for i in 0..<7 {
    let image = UIImage(named: "image \(i)")! 
    imagesUIImages.append(image)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文