Swift advanced (1) basic grammar

Swift advanced (1) basic syntax

Introduction to Swift

Before learning Swift, let s first understand what Swift is

Swift is

In June 2014
The new programming language released, the Chinese name and LOGO are " "

The father of Swift is

Chris Lattner
And also
The author of the compiler,
The main sponsor of the project

Swift version

Swift lasted seven years, from

Swift 1.*
Update to
Swift 5.*
, Has undergone many major changes,
Finally stabilized

API (Application Programming Interface): Application Programming Interface

  • Interface between source code and library

ABI (Application Binary Interface): Application Binary Interface

  • Low-level interface between application and operating system
  • The content involved: target file format, data type size/layout/alignment, function calling convention, etc.

Swift is completely open source, download address: github.com/apple/swift

Swift compilation principle

LLVM compiler

LLVM compiler is generally divided into front-end and back-end

  • Front end: Mainly perform lexical analysis and generate syntax tree
  • Backend: Generate binary code corresponding to the platform

Compilation process

We know that the front end of OC is through

To compile, the front end of Swift is through
To compile

The front-end of different languages may be different, but eventually the binary code of the corresponding platform will be generated through the back-end of the compiler

The entire compilation process is shown in the figure below

  • Swift Code: Swift code we wrote
  • Swift AST: Swift syntax tree
  • Raw Swift IL: Swift-specific intermediate code
  • Canonical Swift IL: More concise Swift-specific intermediate code
  • LLVM IR: The intermediate code of LLVM
  • Assembly: Assembly code
  • Executable: Binary code

For a detailed explanation of the Swift compilation process, please refer to the following website: swift.org/swift-compi...


We open the terminal and type

swiftc -help
, Will print out related instructions, which also shows
Already exists in Xcode

We can find in the app

Right click to display package contents
, Found through this path



Swiftc basic operation walkthrough

Below we can pass some

Some basic operations to understand

1. Let's create a new Swift command line project first

2. Then open the terminal,


3. Then we enter

swiftc -dump-ast main.swift
To view the generated syntax tree

4. We can also enter

swiftc -emit-sil main.swift
Generate the most concise
SIL code

5. We can also enter

swiftc -emit-ir main.swift
LLVM IR intermediate code

6. We can also enter

swiftc -emit-assembly main.swift
Assembly code

Swift basic syntax

Print input in Swift:

print("Hello World")

You can omit the semicolon in one sentence of code in Swift, but if multiple sentences of code are written on one line, they need to be separated by semicolons.

Swift does not need to be written

main function
, Will execute with the first executable code in the global scope as the entry point

Through disassembly, we can see that the bottom layer will execute

main function

Constants and variables


1. Use

Define constants, constants can only be assigned once

No need to specify the type, the compiler will automatically infer

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

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

Write this way to determine the type of a, and then assign a value, no error will be reported

let a: Int a = 10 Copy code

It is also possible to assign values to constants with functions. The function will only determine the value at runtime, so just make sure that the value is assigned before use.

func getNumber() -> Int { return 10 } let a: Int a = getNumber() Copy code

If the type of a is not determined, and the value is not assigned at the beginning of the definition, an error like the following will be reported


1. Use

Define variables

var b = 20 b = 30 Copy code

2. Constants and variables cannot be used before initialization


1. There are single-line comments and multi-line comments in Swift

There is no problem with nesting between comments

//Single line comment /* Multi-line comments /* Multi-line comments */ /* //nested comments */ Copy code


Annotation support
Syntax (same as Markdown)

Grammar only
Valid in the project, invalid in the project

//: # First level title /*: ## Basic syntax */ Copy code

able to pass

Editor -> Show Raw Markup
To preview

The preview effect is as follows


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

let = 5 var = 10 func () { } Copy code

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

Common data types

Common type

  • Value type
    • Enum: Optional
    • Structure (struct): Bool, Double, Float, Int, Character, String, Array, Dictionary, Set
  • Reference type
    • Class

able to pass

Go to this type of API to view

For example, Int type

Integer type

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

On 32bit platform, Int is equal to Int32; On 64bit platform, Int is equal to Int64

The maximum value of an integer: UInt8.max, Int16.min

In general, Int can be used directly

let a: Int8 = 5 duplicated code

Floating point type

Float: 32 bits, precision is only 6 bits

Double: 64 bits, precision at least 15 bits

Floating point does not specify the type, the default is


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


The literal quantity refers to the quantity itself, which is a representation of a fixed value

The following are all literal


General use

Type to indicate whether the judgment is
, Is it

let bool = true copy the code
String, character

How to write strings

let string = "hello" copy the code

Character type should be written

, Otherwise it will be considered a string

Characters can be stored

ASCII characters, Unicode characters

let character: Character = "a" copy the code

Representation of different bases

  • Binary with
  • Octal
  • Hexadecimal starts with
let intDecimal = 17//Decimal let intBinary = 0b10001//Binary let intOctal = 0o21//octal let intHexadecimal = 0x11//Hexadecimal Copy code
Floating point
let doubleDecimal = 125.0//Decimal let doubleDecimal2 = 1.25e2//It is also another way of writing 125.0, which means 1.25 times the power of 10 let doubleDecimal3 = 0.0125 let doubleDecimal4 = 1.25e-2//It is also another way of writing 0.0125, which means the negative power of 1.25 times 10 let doubleHexadecimal1 = 0xFp2//Hexadecimal, which means 15*2^2 (15 times the power of 2), which is equivalent to 60 in decimal let doubleHexadecimal2 = 0xFp-2//Hexadecimal, which means 15*2^-2 (15 times the negative power of 2), which is equivalent to 3.75 in decimal Copy code

Integers and floating point numbers can be added with additional zeros or underscores to enhance readability

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

Type conversion

Integer conversion

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

Integer and floating point conversion

let int = 3 let double = 0.1415926 let pi = Double(int) + double let intPi = Int(pi) Copy code

Literals can be added directly, because number literals have no clear type

let result = 3 + 0.14159 duplicated code


Tuples can be combined with multiple data types

let http404Error = (404, "Not Found") print("The status code is/(http404Error.0)") //You can assign the two values in the tuple separately let (statusCode, statusMsg) = http404Error print("The status code is/(statusCode)") //You can assign only one value in the tuple let (justTheStatusCode, _) = http404Error //You can name the value in the tuple at the time of definition let http200Status = (statusCode: 200, description: "ok") print("The status code is/(http200Status.statusCode)") Copy code

Process control


In Swift

if else
The following conditions can omit the parentheses, but the braces cannot be omitted

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 code

if else
The latter condition can only be
Bool type


var num = 5 while num> 0 { print("num is/(num)") //Printed five times } Copy code

It is equivalent to the C language

Execute once, then judge the conditional loop

var num = -1 repeat { print("num is/(num)") //printed once } while num> 0 Copy code

Not used here

Because of
At the beginning, the increment (++) and decrement (--) operators have been removed


1. Closed interval operator:

, Equivalent to
a <= value <= b

//The first way of writing let names = ["Anna", "Alex", "Brian", "Jack"] for i in 0...3 { print(names[i]) } //The second way of writing let range = 0...3 for i in range { } //The third way of writing let a = 1 let b = 3 for i in a...b { } Copy code

In the loop

The default is
, Add if you need to change

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

Use when you don't need a value

To represent

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

2. Half-open interval operator:

, Equivalent to
a <= value <b

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

3. One-sided interval: Let an interval be as far as possible in one direction

for i in ...3 { } for _ in 3... { } Copy code

4. 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 code

5. Several types of intervals

ClosedRange<Int> 1...3 Half-open range Range<Int> 1..<3 PartialRangeThrough<Int> ...3 Copy code

6. Characters and strings can also use interval operators, but they cannot be used 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 code

7. Interval values with intervals

let hours = 10 let hourInterval = 2 //The value of tickmark, starting from 4, accumulating 2, and not exceeding 10 for tickmark in stride(from: 4, through: hours, by: hourInterval) { print(tickmark) //4, 6, 8, 10 } Copy code


Use the same

C language switch
,the difference is
case, default
Don't write later
big parantheses{}

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 code

Not written by default

, And will not run through to 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 code


Can achieve 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") } //will print number is 1, number is 2 at the same time Copy code

Must ensure that all situations can be handled

Note: Like judging the value of number, all integer conditions must be considered. If you don t want to judge all the conditions, add

That's it

case, default
At least one sentence must follow

If you don t want to do anything, add a


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

If you can guarantee that all situations have been dealt with, you don t have to use it


enum Answer {case right, wrong} let answer = Answer.right switch answer { case .right: print("right") case .wrong: print("wrong") } Copy code

Also supports
Types of

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

Multiple conditions can be judged 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 code

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 code

You can use the underscore to ignore a value

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

Value binding, if necessary

Can also be changed to

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 code



Used to combine conditional statements to filter

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 code

Label statement


To identify the conditions for looping out

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