i am always getting this error when i am trying to give the UIImage parameter to my func makePost. "Value of optional type ‘UIImage?’ must be unwrapped to a value of type ‘UIImage’" I tried something but nothing really worked for me, i only want to put a Image from my Assets to the func.
steven.makePost(image: UIImage(named: "ferrari"), appUser: steven)
func makePost(image: UIImage,appUser: User) {
let post: Post = Post(ersteller: appUser, image: image, datum: "2022")
feed.append(post)
for i in 0..<friends.count {
friends[i].feed.append(post)
}
2
Answers
Creating an image with
UIImage(named: "ferrari")
returns typeUIImage?
because if Swift cannot find the asset with the nameferrari
, it returnsnil
. If you wish to force the compiler to accept onlyUIImage
(unwrapped), you can use!
to force the unwrapping.So your function call will instead be:
steven.makePost(image: UIImage(named: "ferrari")!, appUser: steven)
Note that using
!
is generally unsafe and should be used with caution.The Swift compiler takes type safety very seriously, so if a return isn’t guaranteed, it will be returned as an optional. In this case, the compiler doesn’t know about "ferrari", or you could use this function later with "lamborghini" and forget to add it to your assets, or you call it "Lamborghini". Either way, your app will crash.
Your better option would be to handle the optional
UIImage
in thefunc
itself, like:If ‘image’ is
nil
and not aUIImage
, then nothing will happen, but your app won’t crash.