skip to Main Content

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


  1. Creating an image with UIImage(named: "ferrari") returns type UIImage? because if Swift cannot find the asset with the name ferrari, it returns nil. If you wish to force the compiler to accept only UIImage (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.

    Login or Signup to reply.
  2. 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 the func itself, like:

    func makePost(image: UIImage?,appUser: User) {
    
        // The guard statement safely unwraps your optional and makes sure it
        // is not nil before using it.
        guard let image = image else { return }
    
        // Now it is unwrapped and safe to use.
        let post: Post = Post(ersteller: appUser, image: image, datum: "2022")
        
        feed.append(post)
        
        for i in 0..<friends.count {
            friends[i].feed.append(post)
        }
    }
    

    If ‘image’ is nil and not a UIImage, then nothing will happen, but your app won’t crash.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search