Swift Studying Notes
Reference from the blog from Doyeon from Medium
https://medium.com/doyeona/simple-todo-app-everydaytodo-in-swift-de538a60a142
Other Reference from CSDN and Apple Development Site of Swift
Chapter One . What is swift and what does it feature?
- Swift is a coding language announced by Apple Inc in 2014, aiming to substitute the old Objective-C language.
- Swift is opened to public in 2015, and used by IBM to build back-end.
- It converts lots of class to struct, in the aspect of “strong type” it is very similar to C++ language.However the description system is very similar to fore-end languages like HTML,CSS or JavaScript.
- The “=” in Swift will operate a self-deduction method, the conclusion of a sentence is decided by the right code to the “=”.
Chapter two . The explanations of definitions.
1.The optional type of a variable.
We use a “?” after a type or optional to define it.
let a:Optional=10;//means it can be nil or a decided type of value(10)
let b:Int?=20//means it can be nil or a integer(20)
We can use the force unpacking sign “!” to get the un-nil value of it (if it do not have an un-nil value, it will crash)
print(a)//Gets Optional (10)
print(b)//Gets Optional (20)print(a+b)//cannot be added
print(a!+b!)//10+20=30
The optional type is designed to set default values in convenience
2.The let and var
let means constant , while var means variables, obviously
3.The Conditional Operator (三目运算符) and Branch(分支)
Be like c++
if x > 5 { // no "()"here
print(">5")
} else {
perror("<5") } x > 5 ? print("=5") : () // '()'means do nothing
New operator “??”
IT WILL EXECUTE AFTER OTHER OPERATOR
print(x??0) //if x have a value, use the original value, if not, use the value after the ??
4.If let, if var, guard let, guard var
The difference between if and if let/if var is when the judgement happens on optional constant and variable, it need to unpack first, using the “!”.
And if let is declaring a new constant while conducting the judgement, the function of it is like the “cite” in c++, for creating a temporary constant to use here, as well as to prevent the optional constant is nil.
We can temporarily use the variables to avoid change the variable itself
if let nameNew = name,
let ageNew = age {
print(nameNew + String(ageNew))}//We create new constant/variable to use in here temporarily
Guard let and if let is just the opposite.
5.Range Operators
//not finished yet
6.Strings
Use three double quotation marks
let quotation = """
The White Rabbit put on his spectacles. "Where shall I begin,
please your Majesty?" he asked."Begin at the beginning," the King said gravely, "and go on
till you come to the end; then stop."
"""
The spaces ignored by the string is decided by the first role of it.
Special Characters in String Literals
The escaped special characters \\0
(null character), \\\\
(backslash), \\t
(horizontal tab), \\n
(line feed), \\r
(carriage return), \\"
(double quotation mark) and \\'
(single quotation mark)
An arbitrary Unicode scalar value, written as \\u{n}
, where n is a 1–8 digit hexadecimal number .
let wiseWords = "\\"Imagination is more important than knowledge\\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "\\u{24}" // $, Unicode scalar U+0024
let blackHeart = "\\u{2665}" // ♥, Unicode scalar U+2665
let sparklingHeart = "\\u{1F496}" // 💖, Unicode scalar U+1F496
7.Character and binded String
Char in c++ is equal to character in Swift.
String and character can use + to bind together.
When multiple-role string is going to combine, the second string is directly combine to the end of the first one.
let badStart = """
one
two
"""
let end = """
three
"""
print(badStart + end)
// Prints two lines:
// one
// twothreelet goodStart = """
one
two"""
print(goodStart + end)
// Prints three lines:
// one
// two
// three
We can also insert other code inside a string using \( ).
let multiplier = 3
let message = "\\(multiplier) times 2.5 is \\(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
8.Collection Types in Swift
Array: the same as c++
Set: just values, don’t have any order
Dictionary: values combined with keys merely
If we create collections
//not finished yet
9.What do “:” and “.” suggest in swift
The dots mean to access “property”.
And the colon means “be”
We can attach a bunch of code with large brackets outside
Button {
print("clicked")
} label: {
Text("click")
Or just attach some value or variable , which means these two stuffs is equivalent
Chapter Three. What do Apple Softwares consist and how do they work in both fore-end and back-end?
The softwares get data from the server by JSON( JavaScript Object Notes) codes.
But in stand-alone Apps we can use swift as the data base as well.
//
// Data.swift
// EasyTimer
//
// Created by 何徐宸 on 2022/4/4.
//import SwiftUI
//card data structure
struct Card:Identifiable{
var id = UUID()//identifiable struct must have an id //uuid can generate one
var title:String
var annotation:String
}
We create a structure here with all the essential data members
//
// CardData.swift
// EasyTimer
//
// Created by 何徐宸 on 2022/4/4.
//import SwiftUI
//card data
let cardData:[Card] =
[
Card(title:"10min",
annotation: "study"),
Card(title: "20min",
annotation: "rest")
]
And then we can use another struct to build a group of that structure.
//
// Page002.swift
// Trophy002
//
// Created by 何徐宸 on 2/4/2022.
//import SwiftUIstruct CardView: View {
var card: Card
var body: some View {
ZStack{
Color.pink
.frame(width: 200, height: 300)
.cornerRadius(30)
//.shadow(radius: 15)
VStack{
Text(card.title)
Text(card.annotation)
Button {
print("clicked")
} label: {
Text("click")
} }
}
}
}
//previews
struct CardView_Previews: PreviewProvider {
static var previews: some View {
// CardView(card: carddata[1])
CardView(card:cardData[0])
}
}
When we start to build a view with it, we just
Chapter Four. The commonly used functions
1.Buttons
// Create a button
let btn = UIButton(type: .contactAdd)
view.addSubview(btn)
btn.center = view.center
btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)// The clicking event of a button
func clickMe(btn:UIButton) -> () {
print(#function)
print(btn)
}
2.Preview Provider
struct Page1_Previews: PreviewProvider {
static var previews: some View {
Page1()
}
}//It generates the preview in the Xcode
3.WindowGroup
@main
struct Trophy002App: App {
var body: some Scene {
WindowGroup {
Page1()//It will allow you to add multiple pages in one scene
}
}
}
4.Stacks
ZStack{}//stack in depth, from far to near
VStack{}//stack in height, from up to down
HStack{}//stack in width, from left to right
5.IgnoreSafeArea
.ignoresSafeArea()//will get full screen, including the navigation bar and the bottom bar