TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: passing structure to new view

Forums > SwiftUI

This is some example code. I want to pass the User structure to a new view to display the fields. Not sure whats the best way though. Here is my example code

import SwiftUI
import Combine

struct User: Decodable {
    var id: UUID
    var name: String

    static let `default` = User(id: UUID(), name: "Anonymous")
}

struct ContentView: View {
    @State private var requests = Set<AnyCancellable>()

    var body: some View {
        Button ("Fetch Data") {
            let url = URL(string: "https://www.hackingwithswift.com/samples/user-24601.json")!
            self.fetch(url, defaultValue: User.default) {
                print($0.name)
            }
        }
    }

    func fetch<T: Decodable>(_ url: URL, defaultValue: T, completion: @escaping (T) -> Void) {
        let decoder = JSONDecoder()

        URLSession.shared.dataTaskPublisher(for: url)
        .retry(1)
            .map(\.data)
            .decode(type: T.self, decoder: decoder)
            .replaceError(with: defaultValue)
            .receive(on: DispatchQueue.main)
            .sink(receiveValue: completion)
            .store(in: &requests)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

3      

Here is an example using a similar video Paul did where he fetched both messages and favourates.

I just had this loaded up already but here he uses the same fetch method but I have it in a list with a navigation link pushing a VStack of both who the message is from and what the message is.

import SwiftUI
import Combine

struct Message: Decodable, Identifiable {
    var id: Int
    var from: String
    var message: String
}

struct ContentView: View {
    @State private var requests = Set<AnyCancellable>()
    @State private var messages = [Message]()

    var body: some View {
        NavigationView {
            List(messages) { message in
                NavigationLink(destination:
                    VStack {
                        Text(message.from)
                            .font(.title)
                            .padding()
                        Text(message.message)
                            .padding()
                }) {
                    Text(message.from)
                }
            }
            .navigationBarTitle("Messages")
        }
        .onAppear {
            let url = URL(string: "https://www.hackingwithswift.com/samples/user-messages.json")!

            self.fetch(url, defaultValue: [Message]()) {
                self.messages = $0
            }
        }
    }

    func fetch<T: Decodable>(_ url: URL, defaultValue: T, completion: @escaping (T) -> Void) {

        let decoder = JSONDecoder()

        URLSession.shared.dataTaskPublisher(for: url)
            .retry(1)
            .map(\.data)
            .decode(type: T.self, decoder: decoder)
            .replaceError(with: defaultValue)
            .receive(on: DispatchQueue.main)
            .sink(receiveValue: completion)
            .store(in: &requests)
    }

}

4      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.