By Vu Hieu Nghia
ios development
Vu Hieu Nghia
Developer
Lesson 1: Download Xcode
- Install Xcode in App Store
- Build a project with Xcode use Swift
Lesson 2: Introduce Xcode and Swift by ShipApp
- Run project
- Use iOS
Lesson 3: Basic Swift
a) Use playground to learn
b) Variable and operators
*Variable:
- We can use:
var (can change value)
let (cannot change value)
*Ex:
var mutableVariable = 10
let constantVariable = 20
- We have basic data type in Swift:
Int
Double, Float
String
Character
Bool
*Ex:
var integer: Int = 10
var doubleValue: Double = 10.5
var stringValue: String = "Hello"
var characterValue: Character = "A"
var booleanValue: Bool = true
*Operators
- Assignment: =
*Ex:
var a = 5
var b = 10
- Arithmetic:
+
-
*
/
%
*Ex:
var sum = a + b // 15
var difference = b - a // 5
var product = a * b // 50
var quotient = b / a // 2
var remainder = b % a // 0
- Combined assignment:
+=
-=
*=
/=
%=
*Ex:
a += 5 (a = a + 5, so a become 10)
b -= 3 (b = b - 3, so b become 7)
- Comparison:
==
!=
>
<
<=
>=
*Ex:
let isEqual = (a == b) // false
let isNotEqual = (a != b) // true
let isGreater = (a > b) // true
let isLesser = (a < b) // false
- Logic:
&&
||
!
*Ex:
let x = true
let y = false
let andOperation = x && y // false
let orOperation = x || y // true
let notOperation = !x // false
- Range:
… : Closing range (including both ends)
..< : Open range (includes start but does not include end)
*Ex:
o for i in 1...5 {
print(i) // Print number from 1 to 5
}
o for j in 1..<5 {
print(j) // Print number from 1 to 4
}
c) String
- Declare string:
let greeting = "Hello, World!"
var name = "Alice"
- Connect string:
let fullName = name + " Smith" // "Alice Smith"
name += " Johnson" // "Alice Johnson"
- Interpolate string:
let age = 25
let message = "Hello, my name is \(name) and I am \(age) years old."
- Count the number of characters:
let characterCount = name.count // 14
- Compare:
let isEqual = (greeting == "Hello, World!") // true
let isNotEqual = (name != "Bob") // true
- Operation:
+ Check for empty string
let isNameEmpty = name.isEmpty // false
+ Convert to upper and lower case
let uppercasedName = name.uppercased() // "ALICE JOHNSON"
let lowercasedName = name.lowercased() // "alice johnson"
+ Extract characters
let firstCharacter = name[name.startIndex] // "A"
let secondCharacter = name[name.index(after: name.startIndex)] // "l"
let lastCharacter = name[name.index(before: name.endIndex)] // "n"
+ Replace substring:
let newMessage = message.replacingOccurrences(of: "Alice", with: "Bob") // "Hello, my name
is Bob and I am 25 years old."
+ Split string:
let words = message.components(separatedBy: " ") // ["Hello,", "my", "name", "is", "Alice",
"and", "I", "am", "25", "years", "old."]
+ String combination:
let sentence = words.joined(separator: " ") // "Hello, my name is Alice and I am 25 years old."
- Multiline string:
let multilineString = """
This is a
multiline
string.
"""
- Other useful functions and properties:
o let hasHelloPrefix = greeting.hasPrefix("Hello") // true
o let hasWorldSuffix = greeting.hasSuffix("World!") // true
o let containsName = message.contains("Alice") // true
d) Numbers
- Integer:
+ Signed Integers:
let intExample: Int = 42
let int8Example: Int8 = -128
let int16Example: Int16 = 32000
let int32Example: Int32 = 2147483647
let int64Example: Int64 = 9223372036854775807
+ Unsigned Integers:
let uintExample: UInt = 42
let uint8Example: UInt8 = 255
let uint16Example: UInt16 = 65535
let uint32Example: UInt32 = 4294967295
let uint64Example: UInt64 = 18446744073709551615
- Floating-Point Numbers:
let floatExample: Float = 3.14159
let doubleExample: Double = 3.141592653589793
- Arithmetic operators:
let sum = intExample + 10 // 52
let difference = intExample - 10 // 32
let product = intExample * 2 // 84
let quotient = intExample / 2 // 21
let remainder = intExample % 5 // 2 (Just integer)
- Combined assignment operator:
var number = 10
number += 5 // number = 15
number -= 3 // number = 12
number *= 2 // number = 24
number /= 4 // number = 6
number %= 5 // number = 1
- Comparison operator:
let isEqual = (intExample == 42) // true
let isNotEqual = (intExample != 50) // true
let isGreater = (intExample > 30) // true
let isLesser = (intExample < 50) // true
let isGreaterOrEqual = (intExample >= 42) // true
let isLesserOrEqual = (intExample <= 42) // true
- Convert numeric data type:
let intValue: Int = 42
let doubleValue: Double = Double(intValue) // 42.0
let floatValue: Float = 3.14
let intFromFloat: Int = Int(floatValue) // 3
- Other useful functions and properties:
let negativeValue = -42
let absoluteValue = abs(negativeValue) // 42
let minValue = min(10, 20) // 10
let maxValue = max(10, 20) // 20
let doubleCheck = 3.14159
let isZero = doubleCheck.isZero // false
let isPositive = doubleCheck > 0 // true
e) Boolean and condition logic
- Boolean:
let isSwiftFun: Bool = true
var isLearningFast = false
- Logical operators:
o let a = true
let b = false
let andOperation = a && b // false
let orOperation = a || b // true
let notOperation = !a // false
- Condition structure:
+ if structure:
o let isRaining = true
if isRaining {
print("Take an umbrella.")
}
+ if-else structure:
o let temperature = 30
if temperature > 25 {
print("It's a hot day.")
} else {
print("It's a cool day.")
}
+ if-else if-else structure:
o let score = 85
if score >= 90 {
print("Grade A")
} else if score >= 80 {
print("Grade B")
} else if score >= 70 {
print("Grade C")
} else {
print("Grade F")
}
+ switch structure:
o let grade = "B"
switch grade {
case "A":
print("Excellent!")
case "B":
print("Good job!")
case "C":
print("Well done!")
case "D":
print("You passed!")
case "F":
print("Better luck next time.")
default:
print("Invalid grade.")
}
- Complex conditional logic:
o let age = 20
let hasPermission = true
if age >= 18 && hasPermission {
print("You can enter.")
} else {
print("You cannot enter.")
}
- Using Boolean with loops:
+ While loop:
o var count = 1
while count <= 5 {
print("Count is \(count)")
count += 1
}
+ Repeat-while loop
o var counter = 1
repeat {
print("Counter is \(counter)")
counter += 1
} while counter <= 5
+ for-in loop:
o for number in 1...10 {
if number % 2 == 0 {
print("\(number) is even")
} else {
print("\(number) is odd")
}
}
f) Constant and logical
- Constants:
let maximumNumberOfLoginAttempts = 3
let pi = 3.14159
let welcomeMessage = "Hello, World!"
- Constants data type:
let age: Int = 25
let name: String = "Alice"
let isActive: Bool = true
- Type Safety and Constants:
let number: Int = 10
// let pi: Double = number // Error: Cannot assignment Int to Double
let pi = Double(number) // Right: Assignment Int to Double
- Conditional logic:
+ if structure:
let temperature = 30
if temperature > 25 {
print("It's a hot day.")
}
+ if-else structure:
let temperature = 15
if temperature > 25 {
print("It's a hot day.")
} else {
print("It's a cool day.")
}
+ if-else if-else structure:
let score = 85
if score >= 90 {
print("Grade A")
} else if score >= 80 {
print("Grade B")
} else if score >= 70 {
print("Grade C")
} else {
print("Grade F")
}
+ switch structure:
let grade = "B"
switch grade {
case "A":
print("Excellent!")
case "B":
print("Good job!")
case "C":
print("Well done!")
case "D":
print("You passed!")
case "F":
print("Better luck next time.")
default:
print("Invalid grade.")
}
- Logical operators:
let age = 20
let hasPermission = true
if age >= 18 && hasPermission {
print("You can enter.")
} else {
print("You cannot enter.")
}
- Comparition operators:
let a = 5
let b = 10
let isEqual = (a == b) // false
let isNotEqual = (a != b) // true
let isGreater = (a > b) // false
let isLesser = (a < b) // true
let isGreaterOrEqual = (a >= b) // false
let isLesserOrEqual = (a <= b) // true
g) Array
- Declaring and Initializing Arrays:
+ Declaring an Array
var numbers: [Int] = [1, 2, 3, 4, 5]
let names: [String] = ["Alice", "Bob", "Charlie"]
+ Initialize an empty array:
var emptyArray: [Int] = []
var anotherEmptyArray = [String]()
- Accessing and Changing Elements:
+ Access Elements:
let firstNumber = numbers[0] // 1
let secondName = names[1] // "Bob"
+ Change Element:
numbers[0] = 10 // numbers now is [10, 2, 3, 4, 5]
names[1] = "Bobby" // names now is ["Alice", "Bobby", "Charlie"]
- Add and Remove Elements:
+ Add Elements:
numbers.append(6) // numbers now is [10, 2, 3, 4, 5, 6]
names += ["Dave"] // names now is ["Alice", "Bobby", "Charlie", "Dave"]
+ Insert Elements:
numbers.insert(20, at: 1) // numbers now is [10, 20, 2, 3, 4, 5, 6]
names.insert("Eve", at: 2) // names now is ["Alice", "Bobby", "Eve", "Charlie", "Dave"]
+ Remove Elements:
let removedNumber = numbers.remove(at: 1) // numbers now is [10, 2, 3, 4, 5, 6]
let lastNumber = numbers.removeLast() // numbers bây giờ là [10, 2, 3, 4, 5]
- Loop through Elements
for number in numbers {
print(number)
}
for (index, name) in names.enumerated() {
print("Name at index \(index) is \(name)")
}
- Some useful Methods and Properties:
+ Check the number of elements
let numberOfElements = numbers.count // 5
+ Check for empty array
let isArrayEmpty = emptyArray.isEmpty // true
+ Check for the existence of the element
let containsNumber = numbers.contains(3) // true
let containsName = names.contains("Alice") // true
+ Sort Array
let sortedNumbers = numbers.sorted() // [2, 3, 4, 5, 10]
numbers.sort() // numbers now is [2, 3, 4, 5, 10]
+ Filter Array:
let filteredNumbers = numbers.filter { $0 > 3 } // [4, 5, 10]
+ Transform Array:
let stringNumbers = numbers.map { "\($0)" } // ["2", "3", "4", "5", "10"]
h) Loops
- for-in loop:
+ Loop through an array:
let fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits {
print(fruit)
}
// Output:
// Apple
// Banana
// Cherry
+ Loop through a range:
for number in 1...5 {
print(number)
}
// Output:
// 1
// 2
// 3
// 4
// 5
+ Loop through a dictionary:
let fruitColors = ["Apple": "Red", "Banana": "Yellow", "Cherry": "Red"]
for (fruit, color) in fruitColors {
print("\(fruit) is \(color)")
}
// Output:
// Apple is Red
// Banana is Yellow
// Cherry is Red
- while loop:
var count = 1
while count <= 5 {
print(count)
count += 1
}
// Output:
// 1
// 2
// 3
// 4
// 5
- repeat-while loop:
var counter = 1
repeat {
print(counter)
counter += 1
} while counter <= 5
// Output:
// 1
// 2
// 3
// 4
// 5
- Loop Control Statements:
+ break: The break statement exits the loop immediately.
for number in 1...10 {
if number == 5 {
break
}
print(number)
}
+ continue: The continue statement skips the remainder of the current loop and moves on to the next iteration.
for number in 1...5 {
if number == 3 {
continue
}
print(number)
}
+ fallthrough: The fallthrough statement is not used in a loop but only in a switch statement, allowing transition
to the next case.
- Nesting Loop:
for i in 1...3 {
for j in 1...3 {
print("i = \(i), j = \(j)")
}
}
// Output:
// i = 1, j = 1
// i = 1, j = 2
// i = 1, j = 3
// i = 2, j = 1
// i = 2, j = 2
// i = 2, j = 3
// i = 3, j = 1
// i = 3, j = 2
// i = 3, j = 3
i) Dictionary
- Declaring and Initializing a Dictionary:
+ Declare Dictionary:
var ages: [String: Int] = ["Alice": 25, "Bob": 30, "Charlie": 35]
let capitals: [String: String] = ["France": "Paris", "Japan": "Tokyo", "USA": "Washington, D.C."]
+ Initialize an empty Dictionary:
var emptyDictionary: [String: Int] = [:]
var anotherEmptyDictionary = [String: Int]()`
- Accessing and Changing Values:
+ Access Value:
let aliceAge = ages["Alice"] // Optional(25)
let capitalOfFrance = capitals["France"] // Optional("Paris")
* If the key does not exist, the return value will be nil.
let unknownAge = ages["Unknown"] // nil
+ Changes in value:
ages["Alice"] = 26 // ages now is ["Alice": 26, "Bob": 30, "Charlie": 35]
capitals["France"] = "Marseille" // capitals now is ["France": "Marseille", "Japan": "Tokyo", "USA":
"Washington, D.C."]
+ Add new Value:
ages["Dave"] = 40 // ages bây giờ là ["Alice": 26, "Bob": 30, "Charlie": 35, "Dave": 40]
capitals["Germany"] = "Berlin" // capitals now is ["France": "Marseille", "Japan": "Tokyo", "USA":
"Washington, D.C.", "Germany": "Berlin"]
+ Delete Value:
* You can remove a key-value pair from a dictionary using the removeValue(forKey:) method.
ages.removeValue(forKey: "Bob") // ages now is ["Alice": 26, "Charlie": 35, "Dave": 40]
capitals.removeValue(forKey: "USA") // capitals bây giờ là ["France": "Marseille", "Japan": "Tokyo",
"Germany": "Berlin"]
* You can also assign nil to a key to delete it
ages["Charlie"] = nil // ages now is ["Alice": 26, "Dave": 40]
- Loop through Key-Value Pairs:
+ You can iterate over key-value pairs in a dictionary using a for-in loop.
for (name, age) in ages {
print("\(name) is \(age) years old.")
}
// Output:
// Alice is 26 years old.
// Dave is 40 years old.
+ You can also iterate over individual keys or values.
for name in ages.keys {
print(name)
}
// Output:
// Alice
// Dave
for age in ages.values {
print(age)
}
// Output:
// 26
// 40
- Some useful Methods and Properties:
+ Check the number of elements :
let numberOfElements = ages.count // 2
+ Check for empty dictionary:
let isDictionaryEmpty = emptyDictionary.isEmpty // true
+ Check the existence of a key:
let hasAlice = ages.keys.contains("Alice") // true
let hasBob = ages.keys.contains("Bob") // false
Lesson 4: OOP in Swift
- Object và Class
- Inheritance
- Polymorphism
- Optionals
Lesson 5: Pixel World app
- First Screen
- View Frames
- Auto Layout
- Stack View
- Segues
- Refactoring
- Segue Identifier
- Data models
BÀI 23: Truyền data giữa các màn hình
BÀI 24: We Profile (Auto Layout)
BÀI 25: We Profile (Installed constraint)
BÀI 26: Custom TextField
BÀI 27: Input accessory view
BÀI 28: Unit test cơ bản
BÀI 29: Cấu trúc If let nâng cao
BÀI 30: Add subview
BÀI 31: We Shop – TableView
BÀI 32: UITableView DataSource Delegate
BÀI 33: Collection View
BÀI 34: Collection View – Data
BÀI 35: Collection View – Finish
BÀI 36: Web request and Alamofire
BÀI 37: Parse data
Lesson 8: SwiftUI
- Introduce
- State and Binding
- View Composition
- Modifier
- Navigations
- Tabview
- List
- Animation
- @State – State Management
- @Binding – State Management
- @ObservableObject – State Management
- @Enviroment – State Management