执行Segue时出现Fatal error: Unexpectedly found nil创建UIImage问题
Hey there, I get you don't want this marked as a duplicate since you already understand Optionals and unwrapping—let's zero in on exactly what's happening here with your code and segue flow.
First, let's break down why that crash is happening on line 9:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Your rewardVideoImage is an implicitly unwrapped Optional (UIImageView!), which means when you try to access its .image property, Swift assumes it's never nil. But in this case, it is nil when your selectImage() function runs during viewDidLoad.
Common Causes & Fixes
Your IBOutlet isn't properly connected
This is the most likely culprit. Even though you've declared the outlet in code, the connection between your Storyboard/XIB's UIImageView and this view controller's variable might be broken or missing entirely.
To check:- Open your Storyboard and select this view controller's scene.
- Open the Connections Inspector (the arrow icon in the top-right pane).
- Look for
rewardVideoImageunder "Outlets"—if there's no connection, or it's grayed out, drag a new connection from the outlet to your UIImageView in the Storyboard.
Your view controller isn't being loaded correctly via Segue
If your segue is pointing to the wrong view controller class, or if you're accidentally initializing this view controller manually (instead of letting Storyboard handle it), the IBOutlet won't be populated. Double-check that your segue's destination is set to this exact view controller class in the Storyboard's Identity Inspector.Quick Safety Check (For Debugging)
To avoid crashes while you troubleshoot, you can modify your code to use optional chaining instead of implicit unwrapping. This way, ifrewardVideoImageis nil, the code just skips the assignment instead of crashing:rewardVideoImage?.image = UIImage(named: arrayOfPhotos[randomImageIndex])Once you've fixed the underlying connection issue, you can revert back if you want, but optional chaining is always a safe guard for UI-related code.
Bonus Note on UIImage(named:)
Just to rule out another edge case: even if your image name was wrong, UIImage(named:) returns an optional, but assigning nil to rewardVideoImage.image wouldn't cause this crash—since .image accepts optional values. So the crash is definitely tied to rewardVideoImage itself being nil.
内容的提问来源于stack exchange,提问作者user8969667

