How do I load images with AsyncImage and caching strategies?

Loading images efficiently in SwiftUI can be achieved using the `AsyncImage` view. This component allows for asynchronous fetching of images and can be paired with caching strategies to enhance performance and reduce network load.

In this example, we'll explore how to use `AsyncImage` along with a simple caching mechanism. The caching can be implemented using a custom `ImageCache` class that stores images in memory.

import SwiftUI // ImageCache Class final class ImageCache { private var cache = NSCache() func get(for url: NSURL) -> UIImage? { return cache.object(forKey: url) } func store(image: UIImage, for url: NSURL) { cache.setObject(image, forKey: url) } } struct AsyncImageView: View { @State private var image: UIImage? = nil let url: String private let cache = ImageCache() var body: some View { Group { if let image = image { Image(uiImage: image) .resizable() .aspectRatio(contentMode: .fit) } else { ProgressView() .onAppear { loadImage() } } } } private func loadImage() { guard let url = URL(string: url) else { return } if let cachedImage = cache.get(for: url as NSURL) { image = cachedImage } else { URLSession.shared.dataTask(with: url) { data, response, error in guard let data = data, let fetchedImage = UIImage(data: data) else { return } cache.store(image: fetchedImage, for: url as NSURL) DispatchQueue.main.async { image = fetchedImage } }.resume() } } }

AsyncImage SwiftUI caching strategy ImageCache image loading SwiftUI images