如何在 SwiftUI 中打开可选的图像类型列表

How to unwrap an optional list of type Images in SwiftUI

我有一个全局变量 var list_of_images: [Image]?我在单击按钮时附加到。当我尝试从另一个文件访问它时,我会

ForEach(0..<list_of_images?.count) {
                    list_of_images?[[=10=]]
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                }

但是我收到以下错误: 可选类型 'Int?' 的值必须解包为类型 'Int'

的值

我知道我需要解包 list_of_images,但我尝试了几种方法都没有用,例如

ForEach(0..<list_of_images?.count ?? 0)

等等。

如何展开可选图像列表?

对此最简单的直接回答是使用您提到的相同 ?? 运算符来提供一个空数组:

struct ContentView : View {
    @State var list_of_images : [Image]? = nil
    
    var body: some View {
        ForEach(0..<(list_of_images ?? []).count) {
            list_of_images?[[=10=]]
                .resizable()
                .aspectRatio(contentMode: .fill)
        }
    }
}

但是,我通常会担心存储 Image 本身的想法。我可能会研究另一种存储对它们的引用的方法(路径?名称?UIImages?),而不是迭代。在这种情况下,您可以这样做:

struct ContentView : View {
    @State var imageNames : [String]? = nil
    
    var body: some View {
        ForEach(imageNames ?? [], id: \.self) { imageName in
            Image(imageName)
                .resizable()
                .aspectRatio(contentMode: .fill)
        }
    }
}

此方法不适用于 Image 的数组,因为 Image 不符合 Identifiable

根据评论更新:

struct ContentView : View {
    @State var images : [UIImage]? = nil
    
    var body: some View {
        ForEach(images ?? [], id: \.self) { image in
            Image(uiImage: image)
                .resizable()
                .aspectRatio(contentMode: .fill)
        }
    }
}