Lecture 1: Getting started with SwiftUI


Swift is a functional programming language.

View


A view is a rectangular area on screen. It has the capability to display things inside and receive input from the user. Every rectangular area on screen is a view. Views inside views.
struct ContentView: View {
	var body: some View {
    	Text("Hello, world!")
    }
}
Codes inside {} are actually a function which returns Text("Hello, world!"). var body is not actually stored in memory. It's just calculated by executing the function.
struct ContentView: View {
	var body: some View {
    	Text("Hello, world!").padding(.nil)
    }
}
padding is also a function returns a padded, modified other View which is definitely not Text.
struct ContentView: View {
	var body: some View {
    	return RoundedRectangle(cornerRadious: 25.0)
    }
}
Arguments with labels is very common in Swift. It really makes the code easier to read.

View Combiner


View combiners list views.
struct ContentView: View {
	var body: some View {
    	return ZStack(content: { 
        	RoundedRectangle(cornerRadious: 25.0)
            .stroke(lineWidth: 3)
            .padding(.horizontal)
            .foregroundColor(.red)
        })
    }
}
You could put padding on the ZStack itself. View combiners also behave like a View.
struct ContentView: View {
	var body: some View {
    	return ZStack(content: { 
        	RoundedRectangle(cornerRadious: 25.0)
            .stroke(lineWidth: 3)
            .padding(.horizontal)
            .foregroundColor(.orange)
        })
        .padding(.horizontal)
        .foregroundColor(.red)
    }
}
The combiner itself doesn't actually draw anything. It combines other things that draw like the Rectangle and the text. So the RoundedRectangle might be drawn as orange, not red. Red is just a default color for Views inheriting from their container.

Make code beautiful


Swift can figure out what's going on there. So you don't need to write all the codes above. You can just leave off return, content. See what happended to content. Anytime you have a creation of a struct or even calling a function and you're passing an argument whose value is a function, then as long as it's one of the last arguments, it can be removed from being inside the parenthese. Even if it's the only argument it's same as well.
struct ContentView: View {
	var body: some View {
    	ZStack { 
        	RoundedRectangle(cornerRadious: 25.0)
            .stroke(lineWidth: 3)
            .padding(.horizontal)
            .foregroundColor(.orange)
        })
        .padding(.horizontal)
        .foregroundColor(.red)
    }
}
source:
https://www.youtube.com/watch?v=bqu6BquVi2M&list=PLpGHT1n4-mAsxuRxVPv7kj4-dQYoC3VVu&index=1&ab_channel=Stanford