An Xcode file template that will create your view, observable object, and data object all in one file with sample data.
ObservableObject
.
👉For the @Observable
template, go here.
Add the VOODO.xctemplate to this directory:
~/Library/Developer/Xcode/Templates/File Templates/Custom/
(Click your home directory and then show hidden folders with COMMAND+SHIFT+. )
Note: That full directory might not even exist so you will have to create it.
// View
import SwiftUI
struct PersonView: View {
@StateObject private var oo = PersonOO()
var body: some View {
List(oo.data) { datum in
Text(datum.name)
}
.onAppear {
oo.fetch()
}
}
}
struct Person_Previews: PreviewProvider {
static var previews: some View {
PersonView()
}
}
// Observable Object
import SwiftUI
class PersonOO: ObservableObject {
@Published var data: [PersonDO] = []
func fetch() {
data = [PersonDO(name: "Datum 1"),
PersonDO(name: "Datum 2"),
PersonDO(name: "Datum 3")]
}
}
// Data Object
import Foundation
struct PersonDO: Identifiable {
let id = UUID()
var name: String
}
From here, you can:
- Delete what you don't need
- Keep all the parts in one file
- Break out the parts into separate files
- Change the template to use any naming convention you want
For more information on this architecture and how to work with data in SwiftUI, take a look at this book: Working with Data in SwiftUI.