Swift programming, SwiftUI
In this lession, you will learn:
- Basic Swift programming
- Swift functions, operators
- Define View/Sub Views in SwiftUI, send props to SubViews
- Local state management @State private var
- Anonymous functions with Closures
Create your first project
Installing documents is quite clear. Please
make sure that you installed these items:
- Latest MacOS(version 12, Monterey)
- Xcode and Command Line Tool
- Let’s create a new SwiftUI project after
installing Xcode
-Core Data is used for storing data to local
Database => optional
- Login to your Developer Account if you need
to test your App in Physical devices
Constants/Variables with let, var
Constants and variables must be declared before they’re used. You declare
constants with the let keyword and variables with the var keyword.
var red, green, blue: Double
let π = 3.14159
//You can declare multiple constants or multiple variables on
a single line
var x = 0.0, y = 0.0, z = 0.0
//semicolons are required if you want to write multiple
separate statements on a single line
let cat = "🐱"; print(cat)// Prints "🐱“
//Swift has a basic Boolean type, called Bool
let orangesAreOrange = true
let turnipsAreDelicious = false
Tuples, optional/exclaimation values
Tuples group multiple values into a single compound value. The values within a
tuple can be of any type and don’t have to be of the same type as each other
let http404Error = (404, "Not Found")
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
// Prints "The status code is 404"
print("The status message is \(statusMessage)")
// Prints "The status message is Not Found"
var serverResponseCode: Int? = 404//Optional type can contain nil
value
serverResponseCode = nil
//You can make sure that a variable has "NOT NIL" data:
let assumedString: String! = "this is a string."
Functions and parameters
To use a function, you must define it somewhere in the scope from which you
wish to call it.
func minMax(array: [Int]) -> (min: Int, max: Int) {
var currentMin = 1
var currentMax = 2
//some calculations
return (currentMin, currentMax)
}
//function that return a function
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
return backward ? stepBackward : stepForward
}
//stepBackward, stepForward are 2 functions
func stepForward(_ input: Int) -> Int {
return input + 1
}
Functions and parameters
If you don’t want an argument label for a parameter,
write an underscore (_) instead of an explicit argument label for that parameter.
func someFunction(_ firstParameterName: Int,
secondParameterName: Int,
parameterWithDefault: Int = 12) {
//You can define a default value for any parameter
//..some code here
}
someFunction(1, secondParameterName: 2)
//Variadic Parameters
func arithmeticMean(_ numbers: Double...) -> Double {
//..some code here
return 123
}
arithmeticMean(3, 5)
arithmeticMean(1, 2, 3, 4, 5)
Dictionary in Swift
Dictionary is a type of hash table, each entry in the table is identified using its
key, which is a hashable type such as a string or number.
var interestingNumbers = ["primes": [2, 3, 5, 7, 11, 13, 17],
"triangular": [1, 3, 6, 10, 15, 21, 28],
"hexagonal": [1, 6, 15, 28, 45, 66, 91]]
for key in [Link] {
interestingNumbers[key]?.sort(by: >)
}
print(interestingNumbers["primes"]!)
// Prints "[17, 13, 11, 7, 5, 3, 2]"
let imagePaths = ["star": "/glyphs/[Link]",
"portrait": "/images/content/[Link]",
"spacer": "/images/shared/[Link]"]
for (name, path) in imagePaths {
print("The path to '\(name)' is '\(path)'.")
}
Array of Any Objects
An array of Any object can contain multiple types of values
Views in SwiftUI
A View can be a struct. A screen can contain multiple components, a screen is
also a component. A basic component contains props, state, build-in
components(TextField,Text,…)
struct SelectBodyType: View {
var body: some View {
VStack{
UIHeader(
onPressLeft: {
print("left")
}, onPressRight: {
print("right")
}, title: "")
Spacer()
Text("What's your Body Type ?")
}
}
}
Structures and Classes
Structures and classes have a similar definition syntax. You introduce structures
with the struct keyword and classes with the class keyword
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
//you need to create an instance of the structure or class
let someResolution = Resolution()
let someVideoMode = VideoMode()
//memberwise initializer
let vga = Resolution(width: 640, height: 480)
Structures and Classes
Structures and Enumerations Are Value Types
Classes Are Reference Types
Extensions
Extensions add new functionality to an existing class, structure,
enumeration, or protocol type.
extension Int {
mutating func square() {
self = self * self
}
}
var someInt = 3
[Link]()
// someInt is now 9
extension Rect {
init(center: Point, size: Size) {
//some code here
}
}
Extensions
Let’s see an example of adding methods/properties into UIColor and
Double classes: