Introduction of Swift,

So before we look at Swift, what is Swift

Swift is a new programming language released by Apple at WWDC in June 2014. Its Chinese name and LOGO are “Swift”.

The father of Swift is Chris Lattner, author of the Clang compiler and the main sponsor of the LLVM project

Swift version

After seven years of major changes from Swift 1.* to Swift 5.*, the ABI is finally stable

Application Programming Interface (API) : Application Programming Interface

  • Interface between source code and library

Application Binary Interface (ABI) : Application Binary Interface

  • The underlying interface between an application and the operating system
  • Topics include: object file format, size/layout/alignment of data types, function calling conventions, etc

Swift is fully open source and can be downloaded from github.com/apple/swift

Swift Compilation Principle

The LLVM compiler

LLVM compilers are generally divided into front end and back end

  • Front end: mainly for lexical analysis, generate grammar tree
  • Back end: Generate binaries for the platform

The compilation process

We know that OC’s front-end is compiled with Clang and Swift’s front-end is compiled with SWIFTC

The front-end may differ from language to language, but ultimately the platform’s binaries are generated through the compiler’s back end

The entire compilation process is shown in the figure below

  • Swift Code: the Swift Code we wrote
  • Swift AST: Swift syntax tree
  • Raw Swift IL: Intermediate code specific to Swift
  • Canonical Swift IL: Cleaner Swift-specific intermediate code
  • LLVM IR: Intermediate code for LLVM
  • Assembly: Assembly code
  • Executable

A detailed description of the Swift compilation process can be found at swift.org/swift-compi…

swiftc

When we open the terminal and enter swiftc-help, relevant instructions will be printed, which also indicates that SwifTC has been in Xcode

We can find Xcode in the application and right click to display the package contents to find swifTC

Path: / Applications/Xcode. App/Contents/Developer/Toolchains/XcodeDefault xctoolchain/usr/bin

Swiftc basic operation drills

The following describes some basic operations of SWIFTC

1. Let’s start with a new Swift command-line project

2. Open the terminal and CD to the main.swift path

3. Then enter swiftc-dump-ast main.swift to view the generated syntax tree

4. We can also type swiftc-EMIT -sil main. Swift generates the simplest SIL code

Swiftc-emit – IR main. Swift generates LLVM IR intermediate code

6. We can also type swiftc-emit – Assembly main.swift to generate assembly code

Swift Basic Syntax

Print (“Hello World”)

In Swift, you can omit a semicolon for one line of code, but separate multiple lines of code with a semicolon

Instead of writing the main function, Swift executes with the first globally executable as an entry point

Through disassembly we can see that the underlying main function is executed

Constants and variables

Constants:

1. Use let to define constants, which can only be assigned once

You don’t have to specify the type; the compiler will infer it automatically

let a: Int = 10
let b = 20
Copy the code

2. Its value is not required to be determined during compilation, but must be assigned once before use

So if I write this, I can determine the type of a, and then I can assign it, and I can’t get an error

let a: Int
a = 10
Copy the code

It is also possible to assign a constant to a function, because the value of the function is determined at run time, so just be sure to use the previous assignment

func getNumber() -> Int {
    return 10
}

let a: Int
a = getNumber()
Copy the code

If a is not typed and is not assigned at the beginning of the definition, an error is reported as follows

Variables:

1. Use var to define variables

var b = 20
b = 30
Copy the code

2. Constants and variables cannot be used before initialization

annotation

1.Swift has single-line comments and multi-line comments

Nesting between comments is also fine

// single-line comments /* multi-line comments /* multi-line comments */ /* // nested comments */Copy the code

2. Comments on the Playground support Markup syntax.

Markup syntax works only on Playground, not on projects

//: # 一级标题

/*:
 ## 基础语法
 */
Copy the code

You can preview this using Editor -> Show Raw Markup

The preview looks like this

identifier

1. Identifiers (such as constant names, variable names, function names) can use almost any character

Let 📒 = 5 var 😁 = 10 func 👽() {}Copy the code

The identifier cannot start with a number and cannot contain special characters such as whitespace characters, tabs, and arrows

Common data types

Common type

  • Value types
    • Enum (enum) : Optional
    • Struct: Bool, Double, Float, Int, Character, String, Array, Dictionary, Set
  • Reference types
    • Class (class)

You can view this type of API through Command + Control

For example, Int

Integer types

Integer type: Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64

On 32-bit platforms, Int equals Int32; On 64-bit platforms, Int equals Int64

Uint8.max, int16.min

In most cases, Int is used directly

let a: Int8 = 5
Copy the code

Floating point types

Float: 32 bits, precision is only 6 bits

Double: 64-bit with an accuracy of at least 15 bits

Floating-point types do not specify the type and default to Double

Let a: Float = 2.0 let b = 3.0Copy the code

literal

A literal is the thing itself, a representation of a fixed value

These are all literals

Bool Boolean

Bool Bool Bool Bool Bool Bool Bool Bool Bool Bool Bool Bool Bool

let bool = true 
Copy the code
String, character

The way to write a string

let string = "hello"
Copy the code

The Character type must be Character, otherwise it will be considered a string

Characters can store ASCII characters and Unicode characters

let character: Character = "a"
Copy the code
The integer

Notation in different bases

  • Binary in0bAt the beginning
  • Octal to0oAt the beginning
  • In hexadecimal format0xAt the beginning
Let intDecimal = 17 // decimal let intBinary = 0b10001 // binary let intOctal = 0o21 // octal let intHexadecimal = 0x11 // hexadecimalCopy the code
Floating point Numbers
Let doubleDecimal = 125.0 // Decimal let doubleDecimal2 = 1.25e2 // another way of writing 125.0, Let doubleDecimal3 = 0.0125 let doubleDecimal4 = 1.25e-2 Let doubleHexadecimal1 = 0xFp2 // In hexadecimal, means 15 times 2^2 (15 times 2^2), Equivalent to decimal 60 let doubleHexadecimal2 = 0xfP-2 // in hexadecimal, meaning 15*2^-2 (15 times 2 to the negative second power), equivalent to 3.75 in decimalCopy the code

Integers and floating-point numbers can be added with extra zeros or underscores to improve readability

Let num = 10_0000 let price = 1_000.000_000_1 let decimal = 000123.456Copy the code
An array of
let array = [1, 2, 3, 4]
Copy the code
The dictionary
Let dictionary = ["age" : 18, "height" : 1.75]Copy the code

Type conversion

The integer conversion

let int1: UInt16 = 2_000
let int2: UInt8 = 1
let int3 = int1 + UInt16(int2)
Copy the code

Integer, floating point conversion

Let PI = double (int) + double let intPi = int (PI)Copy the code

Literals can be added directly because numeric literals themselves have no explicit type

Let result = 3 + 0.14159Copy the code

Tuples

A tuple is a combination of multiple data types

let http404Error = (404, "Not Found") print("The status code is \(http404Error.0)") StatusMsg) = http404Error print("The status code is \(statusCode)") Let http200Status = (statusCode: 200, description: "ok") print("The status code is \(http200Status.statusCode)")Copy the code

Process control

if-else

The condition after the if else in Swift can omit the curly braces, but not the curly braces

let age = 10

if age >= 22 {
    print("Get married")
} else if age >= 18 {
    print("Being a adult")
} else if age >= 7 {
    print("Go to school")
} else {
    print("Just a child")
}
Copy the code

The condition after if else can only be Bool

while

Var num = 5 while num > 0 {print("num is \(num)")Copy the code

Repeat -while is equivalent to do-while in C language

Execute once, then judge the conditional loop

Var num = -1 repeat {print("num is \(num)")} while num > 0Copy the code

Num — is not used here because the increment (++) and decrement (–) operators have been removed since Swift3

for

1. Closed interval operator: A… B is the same thing as a <= value <= b

// let names = ["Anna", "Alex", "Brian", "Jack"] for I in 0... 3 {print(names[I])} let range = 0... 3 for I in range {} let a = 1 let b = 3 for I in range {} b { }Copy the code

The default I in the loop is let, plus var if needed

for var i in 0... {3}Copy the code

When no value is needed, it is represented by _

for _ in 0... {3}Copy the code

2. Half-open interval operator: A..

for i in 0.. < 3 {}Copy the code

3. One-sided section: Make one section as far in one direction as possible

for i in ...3 {

}

for _ in 3... {

}
Copy the code

Interval operators can also be used on arrays

let names = ["Anna", "Alex", "Brian", "Jack"] for name in names[0...3] { print(name) } for name in names[2...]  { print(name) } for name in names[...2] { print(name) } for name in names[..<2] { print(name) } let range = ... 5 range.contains(4)Copy the code

5. Several types of intervals

ClosedRange<Int> 1... 3 Range<Int> 1.. <3 PartialRangeThrough<Int>... 3Copy the code

6. The interval operator can also be used for characters and strings, but cannot be used in for-in by default

let stringRange1 = "cc"..." ff" stringRange1.contains("cd") let stringRange2 = "a"..." f" stringRange2.contains("c") let characterRange:ClosedRange<Character> = "\0"..." ~" characterRange.contains("G")Copy the code

7. Interval values with intervals

Let hours = 10 let hourInterval = 2 // Tickmark value, starting from 4 and adding up to 2 and not exceeding 10 for Tickmark in stride(from: 4, through: hours, by: HourInterval) {print(tickmark) // 4,6,8,10}Copy the code

switch

Use the same C language switch, the difference is that case, default do not write curly braces {}

var number = 1

switch number {
case 1:
    print("number is 1")
    break
case 2:
    print("number is 2")
    break
default:
    print("number is other")
    break
}
Copy the code

Break is not written by default and does not run through the following conditions

var number = 1

switch number {
case 1:
    print("number is 1")
case 2:
    print("number is 2")
default:
    print("number is other")
}
Copy the code

Fallthrough can be used to achieve the through-through effect

var number = 1 switch number { case 1: print("number is 1") fallthrough case 2: print("number is 2") default: Print ("number is other")} // Print number is 1, number is 2Copy the code

The Switch must ensure that it can handle all cases

Note: to judge the value of “number”, consider all integer conditions, if not all cases, adddefaultIt is ok

Case and default must be followed by at least one statement

If you don’t want to do anything, just say “break”

var number = 1

switch number {
case 1:
    print("number is 1")
case 2:
    break
default:
    break
}
Copy the code

You may not need to use default if you can ensure that all cases have been handled

enum Answer { case right, wrong }

let answer = Answer.right

switch answer {
case .right:
    print("right")
case .wrong:
    print("wrong")
}
Copy the code

The Switch also supports Character and String

let string = "Jack"

switch string {
case "Jack":
    fallthrough
case "Rose":
    print(string)
default:
    break
}
Copy the code

Switch can judge multiple conditions at the same time

let string = "Jack"

switch string {
case "Jack", "Rose":
    print(string)
default:
    break
}

let character: Character = "a"

switch character {
case "a", "A":
    print(character)
default:
    break
}
Copy the code

The Switch also supports interval matching and tuple matching

let count = 62 switch count { case 0: print("none") case 1.. <5: print("a few") case 5.. <12: print("several") case 12.. <100: print("dozens of") default: print("many") }Copy the code

You can ignore a value using an underscore

let point = (1, 1) switch point: { case (2, 2): print("1") case (_, 0): print("2") case (-2... 2, 0...). : print("3") }Copy the code

Value binding, or let can be changed to var if necessary

let point = (2, 0)
switch point: {
case (let x, 0):
	print(x)
case (0, let y):
	print("2")
case let (x, y):
	print("3")
} 
Copy the code

where

Generally, where is used in conjunction with conditional statements for filtering

let point = (1, -1) switch point { case let (x, y) where x == y: print("on the line x == y") case let (x, y) where x == -y: print("on the line x == -y") case let (x, y): print("\(x), \(y) is just some arbitrary point") } for i in 0... 5 where i == 3 { print(i) }Copy the code

Label statement

Use outer to identify the condition for loop exit

outer: for i in 1... 4 { for k in 1... 4 { if k == 3 { continue outer } if i == 3 { break outer } } }Copy the code