无法分配类型的值' uiimage ??'键入uiimage?' Swift 5
为什么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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是
viewArray
是不是 uiimage的数组。它是可选 uiimage的阵列。好吧,调用Randomelement()
本身会添加一个选择级别,因为数组本身可能是空的。因此,您可以将可选的包装包装包装包装。简单解决方案:说
拆开数组中的选件。现在
随机元
产生可选的。如果您想要一个UIImage,您仍然需要将其解开,但至少只有一个级别可以解开。The problem is that
viewArray
is not an array of UIImage. It is an array of Optional UIImage. Well, callingrandomElement()
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
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.