foreach循环中选项的安全展开不允许构建应用程序



我有一个字典postsAuthorsProfilePicturesURLs[String: URL],它存储了post ID以及帖子作者个人资料图片的相应URL。我在ViewModel中初始化它,最初使用:

@Published var postsAuthorsProfilePicturesURLs: [String: URL] = [:] 

CCD_ 3是从ViewModel中的firebase中提取的。出于测试目的,对于每个post id key,我在ViewModel中的相同方法中为某个图像分配相同的valid url值。问题出在观点本身。在ForEach循环中,我试图显示帖子及其详细信息,以及帖子作者的个人资料图片。为此,我使用AsyncImage

我有以下代码:

AsyncImage(url: homeViewModel.postsAuthorsProfilePicturesURLs[post.id]!) { phase in
if let image = phase.image {
image
.resizable()
.aspectRatio(contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 50))
.frame(width: screenWidth * 0.15, height: screenHeight * 0.15)
} else {
Image(uiImage: UIImage(named: "blank-profile-hi")!)
.resizable()
.aspectRatio(contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 50))
.frame(width: screenWidth * 0.15, height: screenHeight * 0.15)
}
}

并且它可以正确地渲染从url下载的异步图像。然而,我想以更安全的方式打开可选的homeViewModel.postsAuthorsProfilePicturesURLs[post.id]。例如:

if let profilePictureURL = homeViewModel.postsAuthorsProfilePicturesURLs[post.id] {
AsyncImage(url: profilePictureURL) { phase in
if let image = phase.image {
image
.resizable()
.aspectRatio(contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 50))
.frame(width: screenWidth * 0.15, height: screenHeight * 0.15)
} else {
Image(uiImage: UIImage(named: "blank-profile-hi")!)
.resizable()
.aspectRatio(contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 50))
.frame(width: screenWidth * 0.15, height: screenHeight * 0.15)
}
}
}

尽管此更改不允许生成应用程序。使用零检查时也存在同样的问题:

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

我不知道该怎么处理。

编辑:

事实上,我试图通过注释整个View的各个部分来将表达式分解为不同的子表达式,结果发现使用AsyncImage的部分是完全正确的。不正确的是我附加在这个视图的不同部分的confirmationDialog部分。现在该应用程序不会编译,因为这个确认对话框

.confirmationDialog("What", isPresented: $showPostOptions) {
Button("Edit") {
sheetManager.postID = post.id
sheetManager.postText = post.text
sheetManager.whichSheet = .editView
sheetManager.showSheet.toggle()
}

Button("Delete", role: .destructive) {
self.homeViewModel.deletePost(postID: post.id)
}
}

使用AsyncImage.confirmationDialog对代码部分进行注释可使应用程序得以构建。

我设法解决了这个问题,将问题所在的一个视图分解为3个较小的子视图,并在主视图中连接。看来confirmationDialog修饰符和可选展开都是正确的。我以前的观点一定太大了。

相关内容

最新更新