GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Day 73 Solution (Challenge 3rd) problems with creating the ViewModel of EditView.

Forums > 100 Days of SwiftUI

I have created the ViewModel of the EditView. So i am having an error -> "The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions"

My Edit View Code is ->

struct EditView : View {

@State private var viewModel : ViewModel
@Environment(\.dismiss) var dismiss
var onSaveee: (Location) -> Void

var body: some View {
    NavigationStack {
        Form {
            Section {
                TextField("Place name", text: $viewModel.name)
                TextField("Description", text: $viewModel.description)
            }
            Section("Nearby"){
                switch viewModel.loadingState {
                case .loading:
                    Text("Loading...")

                case .loaded:
                    ForEach(viewModel.pages, id: \.pageid) { page in
                        Text(page.title)
                            .font(.headline)
                        + Text(": ") +
                        Text(page.description)
                            .italic()
                    }

                case .failed:
                    Text("Pls try again later")
                }
            }
        }
        .task {
            await viewModel.nearbyPlaces()
        }
        .navigationTitle("Place details")
        .toolbar {
            Button("Save") {
                viewModel.createNewLocation()
                onSaveee(viewModel.newLocation)
                dismiss()
            }
        }
    }
}
init(location: Location, onSave: @escaping (Location) -> Void) {
    self.onSaveee = onSave
    _viewModel = State(initialValue: ViewModel(location: location))
}

}

And my ViewModifier of EditView code is ->

extension EditView {

@Observable
class ViewModel {

    enum LoadingState {
        case loading
        case loaded
        case failed
    }
    var loadingState = LoadingState.loading
    var pages = [Page]()
    var location: Location
    var name: String
    var description: String

    func createNewLocation() {
        var newLocation = location
        newLocation.name = name
        newLocation.description = description
        newLocation.id = UUID()
    }

    func nearbyPlaces() async{
        let urlString = "https://en.wikipedia.org/w/api.php?ggscoord=\(location.latitude)%7C\(location.longitude)&action=query&prop=coordinates%7Cpageimages%7Cpageterms&colimit=50&piprop=thumbnail&pithumbsize=500&pilimit=50&wbptterms=description&generator=geosearch&ggsradius=10000&ggslimit=50&format=json"
        guard let url = URL(string: urlString) else {
               print("Bad URL: \(urlString)")
               return
           }
        do {
            let (data, _) = try await URLSession.shared.data(from: url)
            let items = try JSONDecoder().decode(Result.self, from: data)
            pages = items.query.pages.values.sorted()
            loadingState = .loaded
        } catch {
            loadingState = .failed
        }
    }

    init(location: Location) {
        self.name = location.name
        self.description = location.description
        self.location = location
    }
}

}

   

I agree with @audreyftizpatrick that + might cause it as it has to check multiple times.

You can make a View that take in a Page and format there or a HStack(spacing: 0)

HStack(spacing: 0) {
    Text(title)
        .font(.headline)
    Text(": ")
    Text(description)
        .italic()
}

or use markdown

Text("**\(title)**: *\(description)*")

   

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.