How to pass Data between Views in SwiftUI using a property?

I will demonstrate today how to pass data between views in the SwiftUI by using property.

Let’s Create Second View

I have created second view with one property called data, in that we will display data which will be passed from first screen.

//
// SecondView.swift
// PassDataSwiftUI
//
// Created by Kode on 24/08/22.
//
import SwiftUI
struct SecondView: View {
var data = ""
var body: some View {
Text(data)
}
}
struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView()
}
}

Let’s Create First View

From first view I will pass a sample data to Second View using the property called “data”.

//
// FirstView.swift
// PassDataSwiftUI
//
// Created by Kode on 24/08/22.
//
import SwiftUI
struct FirstView: View {
@State private var showSecondView = false
var body: some View {
Button(action: {
self.showSecondView.toggle()
}, label: {
Text("Open Second View")
})
.sheet(isPresented: $showSecondView){
SecondView(data: "Hello 2nd")
}
}
}
struct FirstView_Previews: PreviewProvider {
static var previews: some View {
FirstView()
}
}
view raw FirstView.swift hosted with ❤ by GitHub

In Second View you will able to see the text “Hello 2nd” by clicking on “Open Second View” Button on First View.

Conclusion

This is only simple JSON. You can try complex JSON responses!

Let me know if you have any questions, comments, or feedback – via Twitter.

Learn Something New. Share To The World.
Happy Coding 🙂