SwiftUI Overview
SwiftUI is Apple's modern UI framework for building declarative user interfaces across all Apple platforms.
Basic SwiftUI View
import SwiftUI
struct ContentView: View {
@State private var users: [User] = []
var body: some View {
NavigationView {
List(users) { user in
VStack(alignment: .leading) {
Text(user.name)
.font(.headline)
Text(user.email)
.font(.subheadline)
.foregroundColor(.gray)
}
}
.navigationTitle("Users")
.onAppear {
fetchUsers()
}
}
}
func fetchUsers() {
guard let url = URL(string: "https://api.example.com/users") else { return }
URLSession.shared.dataTask(with: url) { data, _, _ in
guard let data = data else { return }
if let decoded = try? JSONDecoder().decode([User].self, from: data) {
DispatchQueue.main.async {
self.users = decoded
}
}
}.resume()
}
}
Best Practices
- Use @Published for state management
- Use async/await for API calls
- Update UI on main thread
- Handle errors gracefully
- Use MVVM architecture