Post

Replies

Boosts

Views

Activity

Reply to I Keep getting this error in my swift project.
Same problem, I'm just follow a tutorial on youtube the error in this code let sample = try! container.mainContext.fetch(fetchDescriptor)[0] import SwiftUI import SwiftData struct SampleView: View { let sample: SampleModel var body: some View { VStack{ Text(sample.name) .font(.largeTitle) Image(uiImage: sample.image == nil ? Constants.placeholder : sample.image!) .resizable() .scaledToFit() .clipShape(RoundedRectangle(cornerRadius: 12)) } .padding() } } #Preview { let container = SampleModel.preview let fetchDescriptor = FetchDescriptor<SampleModel>() let sample = try! container.mainContext.fetch(fetchDescriptor)[0] SampleView(sample: sample) } import UIKit import SwiftData @Model class SampleModel { var name: String @Attribute(.externalStorage) var data: Data? var image: UIImage? { if let data { return UIImage(data: data) } else { return nil } } init(name: String, data: Data? = nil) { self.name = name self.data = data } } extension SampleModel { @MainActor static var preview: ModelContainer { let container = try! ModelContainer( for: SampleModel.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true) ) var samples: [SampleModel] { [ .init(name: "Sample 1"), .init(name: "Sample 2"), .init(name: "Sample 3") ] } samples.forEach { container.mainContext.insert($0) } return container } }``` ```swift import UIKit enum Constants { static let placeholder = UIImage(systemName: "photo.fill")! }
Oct ’24