Saturday, November 7, 2026
HomeiOS Developmentios - Secure unwrapping of optionals in foreach loop not permitting app...

ios – Secure unwrapping of optionals in foreach loop not permitting app to construct

[ad_1]

I’ve a dictionary postsAuthorsProfilePicturesURLs[String: URL] that shops submit ID together with corresponding URL for profile image of submit creator. Posts IDs are fetched from firebase in ViewModel. For testing functions, to each submit id key I assign the identical worth of legitimate url for some picture in the identical technique in ViewModel.
The issue is within the view itself. In ForEach loop I am attempting to show posts, with their particulars, together with profilePictures of submit authors. For this I am utilizing AsyncImage.

I’ve the next code:

AsyncImage(url: homeViewModel.postsAuthorsProfilePicturesURLs[post.id]!) { part in
    if let picture = part.picture {
        picture
            .resizable()
            .aspectRatio(contentMode: .match)
            .clipShape(RoundedRectangle(cornerRadius: 50))
            .body(width: screenWidth * 0.15, peak: screenHeight * 0.15)
    } else {
        Picture(uiImage: UIImage(named: "blank-profile-hi")!)
            .resizable()
            .aspectRatio(contentMode: .match)
            .clipShape(RoundedRectangle(cornerRadius: 50))
            .body(width: screenWidth * 0.15, peak: screenHeight * 0.15)
    }
}

and it really works accurately rendering async picture downloaded from the url. I need nonetheless to unwrap the non-obligatory homeViewModel.postsAuthorsProfilePicturesURLs[post.id] within the safer approach. For instance like this:

if let profilePictureURL = homeViewModel.postsAuthorsProfilePicturesURLs[post.id] {
    AsyncImage(url: profilePictureURL) { part in
        if let picture = part.picture {
            picture
                .resizable()
                .aspectRatio(contentMode: .match)
                .clipShape(RoundedRectangle(cornerRadius: 50))
                .body(width: screenWidth * 0.15, peak: screenHeight * 0.15)
        } else {
            Picture(uiImage: UIImage(named: "blank-profile-hi")!)
                .resizable()
                .aspectRatio(contentMode: .match)
                .clipShape(RoundedRectangle(cornerRadius: 50))
                .body(width: screenWidth * 0.15, peak: screenHeight * 0.15)
        }
    }
}

Though this transformation doesn’t enable the app to construct. The identical downside exists when nil checking is used:

if homeViewModel.postsAuthorsProfilePicturesURLs[post.id] != nil

I do not know find out how to deal with this

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments