无法分配类型的值' uiimage ??'键入uiimage?' Swift 5

发布于 2025-01-26 14:08:34 字数 262 浏览 3 评论 0原文

为什么Swift(Xcode)需要一个“ !!”使用RandomeLement()uiimage阵列使用后,double感叹号标记,它本身会给我一个错误。

示例:

someView1.image = viewArray.randomElement()   // right here it tells me to put !!

放置“ !!”之后最后,一切都很好。为什么?

Why does swift(Xcode) requires a "!!" double exclamation mark after using randomElement() to an UIImage array, it by itself gives me an error.

Example:

someView1.image = viewArray.randomElement()   // right here it tells me to put !!

after putting the "!!" at the end everything works fine. Why?

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

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

发布评论

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

评论(1

攒一口袋星星 2025-02-02 14:08:34

问题是viewArray不是 uiimage的数组。它是可选 uiimage的阵列。好吧,调用Randomelement()本身会添加一个选择级别,因为数组本身可能是空的。因此,您可以将可选的包装包装包装包装。

简单解决方案:说

viewArray.compactMap {$0}.randomElement()

拆开数组中的选件。现在随机元产生可选的。如果您想要一个UIImage,您仍然需要将其解开,但至少只有一个级别可以解开。

The problem is that viewArray is not an array of UIImage. It is an array of Optional UIImage. Well, calling randomElement() itself adds a level of Optionality, because the array itself might be empty. Thus you get an Optional wrapping an Optional wrapping a UIImage.

Simple solution: say

viewArray.compactMap {$0}.randomElement()

That unwraps the Optionals in the array. Now randomElement yields an Optional. You will still need to unwrap it if you want a UIImage, but at least there will be only one level to unwrap.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文