SlideShare a Scribd company logo
SwiftUI @
State & Data Flow.
@dana.allwhite
Contents.
🔎 Basic Concepts - Source of Truth, Property Wrapper
🔎 Internal - @State, @Binding
🔎 External - ObservableObject, EnvironmentObject
(Single) Source of Truth
# source of truth - wikipedia
Single source of truth (SSOT) is the practice of structuring information models and associated data schema such that every
data element is mastered (or edited) in only one place. Any possible linkages to this data element (possibly in other areas of the
relational schema or even in distant federated databases) are by reference only. Because all other locations of the data just refer
back to the primary "source of truth" location, updates to the data element in the primary location propagate to the entire system
without the possibility of a duplicate value somewhere being forgotten.
Property Wrapper
To wrap a property with some additional behavior when it’s written and read.
# property wrapper - Swift Language Guide
@State - Source of Truth of View
struct PlayerView : View {
let episode: Episode
var isPlaying: Bool
var body: some View {
VStack {
Text(episode.title)
Text(episode.showTitle).font(.caption).foregroundColor(.gray)
Button(action: {
self.isPlaying.toggle()
}) {
Image(systemName: isPlaying ? "pause.circle" : "play.circle")
}
}
}
}
@State - Source of Truth of View
struct PlayerView : View {
let episode: Episode
@State private var isPlaying: Bool
var body: some View {
VStack {
Text(episode.title)
Text(episode.showTitle).font(.caption).foregroundColor(.gray)
Button(action: {
self.isPlaying.toggle()
}) {
Image(systemName: isPlaying ? "pause.circle" : "play.circle")
}
}
}
}
View Update
View Update
View Update
View Update
@Binding - Reference to Source of Truth
struct PlayerView : View {
let episode: Episode
@State private var isPlaying: Bool
var body: some View {
VStack {
Text(episode.title)
Text(episode.showTitle).font(.caption).foregroundColor(.gray)
// Button(action: {
// self.isPlaying.toggle()
// }) {
// Image(systemName: isPlaying ? "pause.circle" : "play.circle")
// }
PlayButton()
}
}
}
@Binding - Reference to Source of Truth
struct PlayButton: View {
@State var isPlaying: Bool = false
var body: some View {
Button(action: {
self.isPlaying.toggle()
}) {
Image(systemName: isPlaying ? "pause.circle" : "play.circle")
}
}
}
isPlaying
PlayerView
isPlaying
PlayButton
@Binding - Reference to Source of Truth
struct PlayButton: View {
@Binding var isPlaying: Bool = false
var body: some View {
Button(action: {
self.isPlaying.toggle()
}) {
Image(systemName: isPlaying ? "pause.circle" : "play.circle")
}
}
}
A property wrapper type that can read and write a value owned by a source of truth.
@Binding - Reference to Source of Truth
struct PlayerView : View {
let episode: Episode
@State private var isPlaying: Bool
var body: some View {
VStack {
Text(episode.title)
Text(episode.showTitle).font(.caption).foregroundColor(.gray)
PlayButton(isPlaying: $isPlaying)
}
}
}
State Management
State Management - SwiftUI
SwiftUI Components using @Binding
Data from External Source
Property Wrapper Creating Dependency
ObservableObject @ObservedObject Direct
EnvironmentObject @EnviromnetObject Indirect
ObservableObject protocol
final class UserData: ObservableObject {
@Published var showFavoritesOnly = false
@Published var landmarks = landmarkData
}
objectWillChange
ObservableObject - @ObservedObject
struct LandmarkList: View {
@ObservedObject var userData: UserData
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showFavoritesOnly) {
Text("Show Favorites Only")
}
ForEach(userData.landmarks) { landmark in
if !self.userData.showFavoritesOnly || landmark.isFavorite {
// ~~~~
}
}
}
.navigationBarTitle(Text("Landmarks"))
}
}
}
LandmarkList(userData: UserData())
EnvironmentObject - .environmentObject(_)
// SceneDelegate
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView:
LandmarkList()
.environmentObject(UserData()))
self.window = window
window.makeKeyAndVisible()
EnvironmentObject - @EnvironmentObject
struct LandmarkList: View {
@EnvironmentObject private var userData: UserData
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showFavoritesOnly) {
Text("Show Favorites Only”)
}
ForEach(userData.landmarks) { landmark in
if !self.userData.showFavoritesOnly || landmark.isFavorite {
// ~~~
}
}
}
.navigationBarTitle(Text("Landmarks"))
}
}
}
When to Use?
@EnvironmentObject
@ObservableObject
EnvironmentObject - @Environment
.
1. . - single source of truth
2. State source of truth , view function of state .
3. @State framework view change ,
@Binding souce of truth reference
4. @ObservedObject dependency ,
@EnvironmentObject view dependency
Reference.
- SwiftUI by Tutorials (Raywenderlich)
- Data Flow Through SwiftUI (WWDC 2019)
- SwiftUI Essential : Handling User Input
- Data in SwiftUI, Part 1: Data
- Single Source of Truth - Wikipedia

More Related Content

What's hot (10)

A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...
 
Threading
ThreadingThreading
Threading
 
Couchbase & FTS
Couchbase & FTSCouchbase & FTS
Couchbase & FTS
 
15. CodeIgniter editarea inregistrarilor
15. CodeIgniter editarea inregistrarilor15. CodeIgniter editarea inregistrarilor
15. CodeIgniter editarea inregistrarilor
 
Php update and delet operation
Php update and delet operationPhp update and delet operation
Php update and delet operation
 
Introducing jQuery
Introducing jQueryIntroducing jQuery
Introducing jQuery
 
Mysql & Php
Mysql & PhpMysql & Php
Mysql & Php
 
Real Time App with Node.js
Real Time App with Node.jsReal Time App with Node.js
Real Time App with Node.js
 
Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016Laravel, the right way - PHPConference 2016
Laravel, the right way - PHPConference 2016
 
Helping Things to REST
Helping Things to RESTHelping Things to REST
Helping Things to REST
 

Similar to SwiftUI - State & Data Flow

2008.07.17 발표
2008.07.17 발표2008.07.17 발표
2008.07.17 발표
Sunjoo Park
 
Property wrapper and how to use them with mvvm in swift ui i copy
Property wrapper and how to use them with mvvm in swift ui i copyProperty wrapper and how to use them with mvvm in swift ui i copy
Property wrapper and how to use them with mvvm in swift ui i copy
WannitaTolaema
 

Similar to SwiftUI - State & Data Flow (20)

J Query
J QueryJ Query
J Query
 
Getting Started with Combine And SwiftUI
Getting Started with Combine And SwiftUIGetting Started with Combine And SwiftUI
Getting Started with Combine And SwiftUI
 
SwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsSwiftUI and Combine All the Things
SwiftUI and Combine All the Things
 
Wpf Introduction
Wpf IntroductionWpf Introduction
Wpf Introduction
 
Arquitetando seu app Android com Jetpack
Arquitetando seu app Android com JetpackArquitetando seu app Android com Jetpack
Arquitetando seu app Android com Jetpack
 
WPF Concepts
WPF ConceptsWPF Concepts
WPF Concepts
 
Spring boot
Spring boot Spring boot
Spring boot
 
2008.07.17 발표
2008.07.17 발표2008.07.17 발표
2008.07.17 발표
 
Property wrapper and how to use them with mvvm in swift ui i copy
Property wrapper and how to use them with mvvm in swift ui i copyProperty wrapper and how to use them with mvvm in swift ui i copy
Property wrapper and how to use them with mvvm in swift ui i copy
 
JavaEE Spring Seam
JavaEE Spring SeamJavaEE Spring Seam
JavaEE Spring Seam
 
jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journey
 
CIRCUIT 2015 - Content API's For AEM Sites
CIRCUIT 2015 - Content API's For AEM SitesCIRCUIT 2015 - Content API's For AEM Sites
CIRCUIT 2015 - Content API's For AEM Sites
 
Apache Struts 2 Advance
Apache Struts 2 AdvanceApache Struts 2 Advance
Apache Struts 2 Advance
 
Gulshan serialization inJava PPT ex.pptx
Gulshan serialization inJava PPT ex.pptxGulshan serialization inJava PPT ex.pptx
Gulshan serialization inJava PPT ex.pptx
 
FIWARE Global Summit - FIWARE Context Information Management
FIWARE Global Summit - FIWARE Context Information ManagementFIWARE Global Summit - FIWARE Context Information Management
FIWARE Global Summit - FIWARE Context Information Management
 
jQuery, CSS3 and ColdFusion
jQuery, CSS3 and ColdFusionjQuery, CSS3 and ColdFusion
jQuery, CSS3 and ColdFusion
 
Uso di Schema.org per il tuo sito web
Uso di Schema.org per il tuo sito webUso di Schema.org per il tuo sito web
Uso di Schema.org per il tuo sito web
 

Recently uploaded

Recently uploaded (20)

The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System Strategy
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Top 10 Symfony Development Companies 2024
Top 10 Symfony Development Companies 2024Top 10 Symfony Development Companies 2024
Top 10 Symfony Development Companies 2024
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 

SwiftUI - State & Data Flow

  • 1. SwiftUI @ State & Data Flow. @dana.allwhite
  • 2. Contents. 🔎 Basic Concepts - Source of Truth, Property Wrapper 🔎 Internal - @State, @Binding 🔎 External - ObservableObject, EnvironmentObject
  • 3. (Single) Source of Truth # source of truth - wikipedia Single source of truth (SSOT) is the practice of structuring information models and associated data schema such that every data element is mastered (or edited) in only one place. Any possible linkages to this data element (possibly in other areas of the relational schema or even in distant federated databases) are by reference only. Because all other locations of the data just refer back to the primary "source of truth" location, updates to the data element in the primary location propagate to the entire system without the possibility of a duplicate value somewhere being forgotten.
  • 4. Property Wrapper To wrap a property with some additional behavior when it’s written and read. # property wrapper - Swift Language Guide
  • 5. @State - Source of Truth of View struct PlayerView : View { let episode: Episode var isPlaying: Bool var body: some View { VStack { Text(episode.title) Text(episode.showTitle).font(.caption).foregroundColor(.gray) Button(action: { self.isPlaying.toggle() }) { Image(systemName: isPlaying ? "pause.circle" : "play.circle") } } } }
  • 6. @State - Source of Truth of View struct PlayerView : View { let episode: Episode @State private var isPlaying: Bool var body: some View { VStack { Text(episode.title) Text(episode.showTitle).font(.caption).foregroundColor(.gray) Button(action: { self.isPlaying.toggle() }) { Image(systemName: isPlaying ? "pause.circle" : "play.circle") } } } }
  • 11.
  • 12. @Binding - Reference to Source of Truth struct PlayerView : View { let episode: Episode @State private var isPlaying: Bool var body: some View { VStack { Text(episode.title) Text(episode.showTitle).font(.caption).foregroundColor(.gray) // Button(action: { // self.isPlaying.toggle() // }) { // Image(systemName: isPlaying ? "pause.circle" : "play.circle") // } PlayButton() } } }
  • 13. @Binding - Reference to Source of Truth struct PlayButton: View { @State var isPlaying: Bool = false var body: some View { Button(action: { self.isPlaying.toggle() }) { Image(systemName: isPlaying ? "pause.circle" : "play.circle") } } } isPlaying PlayerView isPlaying PlayButton
  • 14. @Binding - Reference to Source of Truth struct PlayButton: View { @Binding var isPlaying: Bool = false var body: some View { Button(action: { self.isPlaying.toggle() }) { Image(systemName: isPlaying ? "pause.circle" : "play.circle") } } } A property wrapper type that can read and write a value owned by a source of truth.
  • 15. @Binding - Reference to Source of Truth struct PlayerView : View { let episode: Episode @State private var isPlaying: Bool var body: some View { VStack { Text(episode.title) Text(episode.showTitle).font(.caption).foregroundColor(.gray) PlayButton(isPlaying: $isPlaying) } } }
  • 19. Data from External Source Property Wrapper Creating Dependency ObservableObject @ObservedObject Direct EnvironmentObject @EnviromnetObject Indirect
  • 20. ObservableObject protocol final class UserData: ObservableObject { @Published var showFavoritesOnly = false @Published var landmarks = landmarkData } objectWillChange
  • 21. ObservableObject - @ObservedObject struct LandmarkList: View { @ObservedObject var userData: UserData var body: some View { NavigationView { List { Toggle(isOn: $userData.showFavoritesOnly) { Text("Show Favorites Only") } ForEach(userData.landmarks) { landmark in if !self.userData.showFavoritesOnly || landmark.isFavorite { // ~~~~ } } } .navigationBarTitle(Text("Landmarks")) } } } LandmarkList(userData: UserData())
  • 22. EnvironmentObject - .environmentObject(_) // SceneDelegate let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: LandmarkList() .environmentObject(UserData())) self.window = window window.makeKeyAndVisible()
  • 23. EnvironmentObject - @EnvironmentObject struct LandmarkList: View { @EnvironmentObject private var userData: UserData var body: some View { NavigationView { List { Toggle(isOn: $userData.showFavoritesOnly) { Text("Show Favorites Only”) } ForEach(userData.landmarks) { landmark in if !self.userData.showFavoritesOnly || landmark.isFavorite { // ~~~ } } } .navigationBarTitle(Text("Landmarks")) } } }
  • 26. . 1. . - single source of truth 2. State source of truth , view function of state . 3. @State framework view change , @Binding souce of truth reference 4. @ObservedObject dependency , @EnvironmentObject view dependency
  • 27. Reference. - SwiftUI by Tutorials (Raywenderlich) - Data Flow Through SwiftUI (WWDC 2019) - SwiftUI Essential : Handling User Input - Data in SwiftUI, Part 1: Data - Single Source of Truth - Wikipedia