Swift study notes (1) basic grammar


foreword

浅学一下Swift,这篇笔记做个记录


development tools

It is still Xcode, so I won’t introduce much about Xcode.

insert image description here

Variables and Constants

The let keyword and the var keyword are used to represent constants and variables respectively. Whether it is let or var, the function is to take a name for a specific value. This method is called the declaration of the value. Within the effective scope of the value, developers can use these names to obtain specific values. There are two basic concepts in programming: value and expression.
It is understood that the magnitude is the result. 3 is an integer value, and the string hello is a string value.
An expression can be understood as a calculation process, and the result is a magnitude. 1+2 is an expression whose result is the magnitude 3.
hello+world is also an expression whose result is the magnitude hello world.
Most expressions consist of quantities and operators.

Definition and use of variables and constants

//引入UIKit框架
import UIKit
//定义一个变量,赋值为字符串“hello,playground”
var greeting = "Hello, playground"
//定义一个变量,赋值为字符串“hello,playground”
var greeting = "Hello, playground"



//这句代码和下面这句代码等效

//声明字符串变量
var str: String
//对字符串变量str进行赋值
str = "hello,playground"




//量值的打印
print(str)
//在使用常量或者变量时,开发者可以直接通过名称来调用对应的量值,
str = "newValue"

//在str后追加hello
str = str + "hello"

Swift also supports declaring multiple constants or variables in the same line statement, but must follow the principle of clear type

var a = 1, b = 2, c = "string"
var a2 : Int = 1, b2 : Float = 2.9, c2 : String = "string"

If multiple variables are declared in the same line of code and no initial value is provided, the type can be specified by specifying the type of the last variable as a whole

var one, two, three : Int

The var one, two, and three declared in the above code are all Int type variables

(1) The Swift language is a very fast and concise language. It allows developers to omit semicolons and automatically separate statements with newlines. At the same time, it supports writing multiple sentences of code in one line. In this case, semicolons are required to separate statements. For example:
var str:String;str = “hello,playground”;print(str)
(2) The type inference of the Swift language is a very good feature of the Xcode compiler. In actual development, developers should use it as much as possible this characteristic.
(3) If you need to modify the value of the variable, you can directly reassign the variable. It should be noted that the type of the assigned value must be consistent with the type of the variable.

Naming Conventions for Variables and Constants

In the Swift language, the naming rules for constants and variables are very broad, and can include Unicode characters and numbers. It should be noted that reserved keywords cannot be used as the names of constants or variables, such as let and var. value name to declare. In addition, the names of constants and variables cannot start with numbers, and symbols such as spaces, mathematical symbols, tabs, and arrows cannot be used in names.insert image description here

You can also use interspersed numbers for naming, and note that numbers cannot be used as the beginning:
//Names containing numbers var pen2 = "pen"
can also be named with underscores: //Names with underscores
var swift = "swift"

Although Swift supports a wide range of naming methods, in actual development, a good naming style can greatly improve coding efficiency and code readability. The official Swift language documentation uses camel case naming. The so-called hump naming refers to the splicing of names with words. The first letter of the name is generally lowercase, and the first letter of each word after that is capitalized, and the other letters are all lowercase. The example is as follows: //Hump naming var userName = "Hun
Shao
"

(1) Unicode (unicode, universal code, single code) is an industry standard in the field of computer science, including character sets, encoding schemes, etc. Unicode was created to solve the limitations of traditional character encoding schemes. It sets a unified and unique binary encoding for each character in each language to meet cross-language and cross-platform text conversion , processing requirements. Unicode began research and development in 1990 and was officially announced in 1994.
(2) Naming in Swift also has some customary rules, for example, the first letter of value attributes will be lowercase, and the first letter of class names, object names, and structure names will be uppercase.
(3) If you really need to use reserved keywords for naming, you can use 符号迚行包装,但是除非 万不得已,开収中尽量不要使用这种斱式命名,包装示例如下: //用预留关键字迚行命名 var var` = 2

note

Single-line comments and multi-line comments are the same as OC comments.
But Swift can do annotation nesting.

//单行注释//注释中的注释 /*
多行注释
/*
*/
注释 注释 */

Get to know basic data types

Integer data in the Swift language is divided into signed integer data and unsigned integer data. The so-called signed and unsigned, the popular understanding is that there are signs and no signs.
For unsigned integers, Swift provides data types of 5 types and 4 storage spaces, and the 4 storage spaces occupy 8 bits, 16 bits, 32 bits and 64 bits of memory respectively. Use the Xcode development tool to create a new Playground, name it BasicDataType, and write the following demonstration code:
For unsigned integers, Swift provides 5 types of data types with 4 storage spaces, and the 4 storage spaces occupy 8 bits of memory. 16-bit, 32-bit and 64-bit. Use the Xcode development tool to create a new Playground, name it BasicDataType, and write the following demo code:

//8 位无符号整型数的最大值 255 
var a1 = UInt8.max
//16 位无符号整型数的最大值 65535 
var a2 = UInt16.max
//32 位无符号整型数的最大值 4294967295
var a3 = UInt32.max
//64 位无符号整型数的最大值 18446744073709551615 
var a4 = UInt64.max

4 variables a1, a2, a3, a4 are created in the above code. In the Swift language, the integer data type is actually implemented in the form of a structure, and the max attribute can obtain the maximum value of the current type. Readers may have doubts, which type should be chosen to express unsigned integers in actual development? As mentioned above, there are actually five unsigned integers in the Swift language, and one is UInt type, this type of compiler will automatically adapt, it is UInt64 on a 64-bit machine, and UInt32 on a 32-bit machine, the sample code is as follows:

var a6 = MemoryLayout<UInt>.size

MemoryLayout is an enumeration defined in the Swift standard library. As the name implies, it is used to obtain memory-related information. MemoryLayout is a generic usage. Calling its size property can obtain the number of bytes of memory space occupied by a certain data type.
Signed integer data is very similar to unsigned integer data, except that the first binary bit is a sign bit, which is not included in numerical calculations. The sample code is as follows:

var maxInt8 = Int8.max //127
var mimInt8 = Int8.min //-128
var maxInt16 = Int16.max //32767
var minInt16 = Int16.min //-32768
var maxInt32 = Int32.max //2147483647
var minInt32 = Int32.min //-2147483648
var maxInt64 = Int64.max //9223372036854775807 var minInt64 = Int64.min //-9223372036854775808 var intSize = sizeof(Int) //8位

Corresponding to the max attribute, the min attribute is used to obtain the minimum value of integer data.

floating point data

var b = MemoryLayout<Float>.size 
var b1 = MemoryLayout<Float32>.size 
var b2 = MemoryLayout<Float64>.size 
var b3 = MemoryLayout<Float80>.size 
var c = MemoryLayout<Double>.size
//4字节 
//4字节 
//8字节 
//16字节 
//8字节

The Swift language supports the use of scientific notation to represent numbers. In decimal, use e to represent 10 to the nth power. In hexadecimal, use p to represent 2 to the nth power. The sample code is as follows:

var sum = 1.25e3 //1.25*(10^3) ​​= 1250 var sun2 = 0x1p3 //1*(2^3) = 8

There is also a very interesting feature in the Swift language. Whether it is integer data or floating-point data, you can add any number of 0s before the number to fill the number of digits, or you can add an underscore to the number to separate, and then To increase readability, these operations will not affect the original value, but improve the friendliness of programming for developers and make the structure of the code clearer. Examples are as follows:

var num1 = 001.23 //1.23
var num2 = 1_000  //1000
var num3 = 1_000.1_ 001 //1000.1001

Boolean data

The Boolean type is often called a logical type. Readers familiar with the Objective-C programming language may understand that in the Objective-C language, the Bool type is not a logical Boolean type in the strict sense. Zero and not can be used in Objective-C. Zero to express logical false and logical true. It is different in the Swift language, the Bool type of the Swift language is very strict, there are only two values ​​of true and false, which represent true and false respectively. Similarly, in the conditional statement of the Swift language and the statement requiring logical judgment, the value of the conditional expression used must also be of type Bool.

Two special primitive data types

The Swift language also supports two special basic data types, namely tuple type and optional value type. Tuples are very commonly used in actual development. Developers can use tuples to create custom data types with any combination of data types; optional value types are a major feature of the Swift language. Through optional value types, Swift language logarithmic values Strict control was carried out for the air.

tuple

Tuples are one of the important data types in the Swift language. Tuples allow some unrelated types to be freely combined into new collection types. The Objective-C language does not support data types such as tuples, which will cause trouble for developers in many cases. Analogous to a situation in life, the tuple type is similar to the package in daily life. Now various service industries have launched many distinctive packages for customers to choose, so as to provide customers with one-stop service. Tuples provide such a programming structure. Imagine a situation in programming: a product has a name and a price. Using tuples can simulate this type of product very well. Examples are as follows:

//创建钢笔元组类型,其中有两种类型,字符串类型的名称和整数类型的价钱
var pen : (name : String, pricr : Int) = ("钢笔", 2)

The above code specifies the names of the parameters when creating the tuple, that is, the name parameter is name, and the price parameter is price. Developers can use these parameter names to obtain the values ​​of each parameter in the tuple.

var name = pen.name
var price = pen.price

When creating a tuple, you do not need to specify the parameter name, and the tuple will automatically assign a subscript to each parameter, and the subscript value will increase sequentially from 0

var car : (String, Int) = ("奔驰", 20000000)
var carName = car.0
var carPrice = car.1

After the tuple instance is created, developers can also decompose it by specifying variables or constants,

//不指定参数名称的元组
var car : (String, Int) = ("奔驰", 2000000)

//进行元组的分解
var (theName, thePrice) = car
//此时theName变量被赋值为“奔驰“, thePrice被赋值为2000000
print(theName, thePrice)

The above code decomposes each component element of the tuple instance car into specific variables. There is one point that readers need to pay attention to.The decomposed variables must correspond to the elements in the tuple one by one (the number is equal), otherwise the compiler will make an error.
The print() function is a printout function. The print() function can receive multiple parameters, which can be separated by . Sometimes
, developers may not need to obtain the values ​​of all elements in a tuple instance. In this case In this case, developers can also anonymously receive some elements that do not need to be acquired, as shown in the following examples:

//不指定参数名称的元组
var car : (String, Int) = ("奔驰", 2000000)
//进行元组的分解,将Int型参数进行匿名
var (theName, _) = car
//此时theName被赋值为“奔驰”
print(theName)

In the Swift language, the symbol " " is often used to represent the anonymous concept, so " " is also called an anonymous identifier. The above code actually decomposes only the first element (String type) in the tuple car.
Although tuples are very convenient to use, they are only suitable for the combination of simple data. For data with complex structures, structures or classes should be used to realize them.

optional value type

Optional value type (Optional type) is a unique type of Swift language. First of all, the Swift language is a language that places great emphasis on type safety. When a developer uses a certain variable, the compiler will try its best to ensure the clarity of the type and value of the variable to reduce uncontrollable factors in programming. However, in actual programming, any type of variable will encounter a situation where the value is empty. There is no mechanism in the Objective-C language to specifically monitor and manage variables that are empty. The security of the program is all manually controlled by the developer. . The Swift language provides a wrapping method to perform Optional wrapping on common types to realize the monitoring of null values.
In the Swift language, if you use a variable that has not been assigned a value, the program will directly report an error and stop running. Readers may think that if a variable is not assigned an initial value when it is declared, it may be assigned a value later in the program, so what should we do for this application scenario of "declaration first and then assignment"? In Objective-C, this problem is easy to solve, just need to judge whether the variable is nil when using it. Is it possible to do the same in Swift? Use the following code to test:
In the Swift language, if you use an unassigned variable, the program will directly report an error and stop running. Readers may think that if a variable is not assigned an initial value when it is declared, it may be assigned a value later in the program, so what should we do for this application scenario of "declaration first and then assignment"? In Objective-C, this problem is easy to solve, just need to judge whether the variable is nil when using it. Is it possible to do the same in Swift? Use the following code to experiment:

var obj:String 
if obj==nil {
    
    
}

insert image description here
After writing the above code, you can see that the Xcode tool still throws an error message. In fact, in the Swift language, ordinary types that have not been initialized are not allowed to be used, even if they are used for null judgment processing. Of course, it is not possible to perform comparison operations with nil. This mechanism greatly reduces the uncontrollability of the code. Therefore, developers must ensure that variables are initialized before use, the code is as follows:


var obj0 : String
obj0 = "HS"
print(obj0)

However, the above approach is not commonly used in actual development. If a variable may be nil logically, the developer needs to wrap it as an Optional type. Rewrite the above code as follows:

var obj : String?
if obj == nil {
    
    
    
}

At this point the code should run normally. Analyzing the above code, when declaring the obj variable, here it is declared as a String? type,Add the symbol "?" after the ordinary type to wrap the ordinary type into an Optional type.
The Optional type does not exist independently. It is always attached to a specific data type. The specific data type can be a basic data type, a structure, or a class. The Optional type has only two values, which readers can understand as:

  • If the magnitude corresponding to its attachment type has a concrete value, it is a wrapper for the concrete value.
  • It is nil if the magnitude corresponding to its attachment type does not have a specific value.
  • The nil reader in the Optional type can also be understood as a value that represents empty

The Optional type is a kind of packaging for ordinary types, so it needs to be unpacked when it is used, and the unpacking will use the operator "!" in Swift. The two operators "?" and "!" are a nightmare for many Swift language beginners. If readers understand the Optional type, it will be much easier to understand and use these two operators. First of all, it should be noted that the "?" symbol can appear after the type or after the instance. If it appears after the type, it represents the Optional type corresponding to this type. If it appears after the instance, it represents optional. The call of the chain will be introduced in detail in the following chapters. The "!" symbol can also appear behind the type and instance. It appears after the type and represents an implicitly parsed grammatical structure, which will be introduced in later chapters; it appears after the instance represents the unpacking of the Optional type instance operate. Examples are as follows:

//声明obj为String?类型
var obj : String? = "HS"
//进行拆包操作
obj!

Readers need to pay attention, when using "!" to unpack the Optional value, you must ensure that the value to be unpacked is not nil, otherwise the program will run incorrectly. You can use the if statement to make a security judgment before unpacking. The example is as follows:

var obj : String? = "HS"
if obj != nil {
    
    
    obj!
}

If obj has a value, the if-let structure will create a temporary constant tmp to receive the unpacked value of obj, and execute the corresponding code block when if is true. In the executed code block, developers can directly use the unpacked The packaged obj value is tmp. If obj is nil, it will enter the code block where if is false, and the developer can reassign obj to use in the else code block. This if-let structure actually completes the three processes of judging, unpacking, and binding the unpacked value to a temporary constant.
In the if-let structure, multiple values ​​of the Optional type can also be bound at the same time, separated by commas, examples are as follows:

//if-let多Optional值绑定
var obj1 : Int? = 1
var obj2 : Int? = 2
if let tmp1 = obj1, let tmp2 = obj2 {
    
    
    print(tmp1, tmp2)
}

When binding multiple values ​​of the Optional type at the same time, the binding will succeed only if all the Optional values ​​are not nil, and the code execution will enter the if is true code block.

//if-let多Optional值绑定
var obj1 : Int? = 1
var obj2 : Int? = 2
if let tmp1 = obj1, let tmp2 = obj2, tmp1 < tmp2 {
    
    
    print(tmp1, tmp2)
}

The above code will only enter the if is true code block when obj1 is not nil, obj2 is not nil and the unpacking value corresponding to obj1 is smaller than the unpacking value corresponding to obj2, that is, print the bound tmp1 and tmp2 value.
For a variable of optional value type, we need to unpack it every time we use it, which is relatively troublesome. In fact, there is another syntax in Swift: implicit parsing. Implicit parsing is suitable for such a scenario: when we make it clear that a variable is initially nil and must be assigned a value before it is used later, we can declare it as an optional value for implicit parsing, and then perform Use, there is no need for unpacking operations, for example, the following code will generate a runtime error:insert image description here
Will compile errors, because obj4 is not unpacked

//声明obj4为隐式解析的变量
var obj4 : Int!
obj4 = 3
//使用时,无须再进行拆包操作,Swift会自动帮我们拆包
print(obj4 + 1)

alias the type

Languages ​​such as C, C++, and Objective-C all provide keywords such as typedef to take an alias for a certain type. In the
Swift language, the keyword typealias is used to achieve the same effect. Examples are as follows:


//为Int类型取一个别名Price
typealias Price = Int
//使用Price代替Int, 效果完全一样
var penPrice : Price = 100

The above code takes the alias Price for the Int type. In the subsequent use, the Price type is exactly the same as the Int type. In actual development, flexible use of typealias to alias the type can optimize the readability of the code.

mock interview

(1) The symbols "?" and "!" are two very common symbols in Swift projects. Please briefly describe your understanding of them. Tips for answering key points: 1 First understand from the two aspects of type and instance, "?" appears after the type to indicate the Optional type, and appears after the instance to indicate the optional chain call
. "!" Appearing after the type means default implicit parsing, and appearing after the instance means forced unpacking. 2 These two symbols are related to the Optional type in Swift. The Optional type is a
way Whether a variable can be empty should be determined logically, rather than unpredictable and uncontrollable . 3The combination of if-let structure and Optional type value can write elegant and safe logic code.
Core understanding content:
Have an in-depth understanding of the Optional type in Swift. (2) What are the advantages of decimal, binary, octal, and hexadecimal, and in what scenarios are they used. Tips for answering key points: 1. The advantages of the decimal system needless to say, almost all mathematical calculations in daily life use the decimal system
. 2Binary is the most convenient way for computers to understand the base system. The high and low level states are very easy to represent binary 0 and 1, and it is also the
most stable way to store data in the computer. 3 Octal and hexadecimal are actually binary aggregation methods. In octal, each digit can represent
3 bits in binary, and in hexadecimal, each digit can represent 4 bits in binary, which greatly shortens the The length of the binary number and is readable. Hexadecimal is often used to represent color data.
Core understanding content:
the principle of base and conversion method.
(3) Are there only two data types, var and let, in the Swift language?
Tips for answering key points: 1. This proposition is very wrong. In Swift, var and let are not data types, but two methods for declaring variables.
Mode. 2Swift is a strong data type, just like C, C++, Objective-C, Java and other languages, when variables are declared, their data
Example analysis:
the type has already been determined, sometimes we do not specify it explicitly, because Xcode has automatic type inference Function. The data types in 3Swift include basic data types and reference data types, and basic data types include integers, floating-point types,
Boolean types, tuples, etc.
Core understanding content:
understand the meaning of data types, understand the relationship between variables and data types, and understand the automatic type inference function of Xcode.

Character, string and collection types

In program development, the use of strings is essential, which is a very important data type in programming. In fact, strings are also a collection of characters. Some languages ​​do not have an independent string type, such as C language, which often uses character arrays as string types. Objective-C language encapsulates the object-oriented string type NSString, and encapsulates a large number of related methods in it. . And Swift is a language that weakens pointers, it provides String type and Character type to describe strings and characters.

string type

As the name suggests, the string type is a combination of a string of characters, which is widely used in development. The scene logic such as the name of the product, the class of the student, and the lyrics of the music need to be processed through the string.

var str = "hello, world"

var str = ""

The value of a string variable is an empty string and the value of a string variable is nil are two completely different concepts. If an Optional type variable is not assigned a value, it is nil. If it is assigned an empty string, it is not nil. .
In the Swift language, the String type is actually a structure. In fact, the integer, floating-point, and Boolean types learned in the previous chapters are also implemented by the structure. The structure in the Swift language is very powerful, and it can define properties and methods like a class.


var str : String = "Hello, playground"
print(str)
str = ""
print(str)

str = String()
print(str)

str = String("hello")
print(str)

str = String(666)
print(str)

str = String(6.66)
print(str)

str = String("a")
print(str)

str = String(false)
print(str)

str = String(describing: (1, 2.0, true))
print(str)

str = String(describing: [1, 2, 3])
print(str)

str = String(format: "我是%@", "会少")
print(str)

insert image description here
The String type provides many overloaded construction methods, and developers can pass in different types of parameters to construct the required string. In fact, the String type in the Swift language provides a wide range of construction methods, and even other types can be
converted into strings through construction methods, as shown in the following examples:

var str : String = "Hello, playground"
print(str)

str = String(describing: Int.self)
print(str)

var a = Int(1.5)
print(a)
var b = Float(a)
print(b)

insert image description here

combination of strings

The String type in Swift implements overloading of the "+" operator, that is, developers can directly use the "+" symbol to
concatenate multiple string combinations into a new string.


var c1 = "Hello"

var c2 = "world"

var c3 = c1 + " " + c2
print(c3)

insert image description here
Through the addition operator, developers can easily combine string variables. Sometimes developers need to insert another string in the middle of a string. In addition to using the formatted construction method, Swift also provides A very convenient string interpolation method

String interpolation using ()

var d = "Hello\(123)"
print(d)
var d2 = "Hello\(d)"
print(d2)
var d3 = "Hello\(1 + 2)"
print(d3)

insert image description here
The "()" structure can convert other data types into string types and insert them into the corresponding position of the string data, or insert the result into the original string after performing simple operation logic. This method is very convenient for string The formatting is widely used in development.

character type

The character type is used to represent a single character, such as numeric characters, English characters, symbol characters and Chinese characters, etc. can be represented by the character type
, and the characters in the string can also be decomposed by traversing the string.

Similar to Char in C language, Character is used in Swift language to describe character types, and both Character type and String type occupy 16 bytes of memory space. In Swift, you can use the MemoryLayout enumeration to obtain the memory space occupied by a certain type, and its unit is bytes. The example is as follows:

print(MemoryLayout<String>.size)

insert image description here
Character is used to describe a character. We combine a group of characters into an array to construct a string. Examples are as follows
:


var e : Character = "a"
var e2 : [Character] = ["H", "E", "L", "L", "O"]
var e3 = String(e2)
print(e, e2, e3)

insert image description here
Use for-in traversal to disassemble the characters in the string. This method is sometimes very useful. For-in traversal is an important code flow structure in the Swift language. The String type implements the iterator-related protocol by default. Directly traversing it can extract each character element in the string. The sample code is as follows:

let name = "China"
for character in name {
    
    
    print(character)
}

insert image description here
The for-in structure is an important loop structure. In the sample code above, the in keyword needs to be an iterable type, and the in keyword is preceded by the elements taken from the iterator for each loop. The type is automatically inferred by the Xcode compiler

escape character

The Swift language is similar to the C language. In addition to some conventional visible characters, it also provides some special-purpose escape characters, which
can express specific meanings through special symbol combinations. Examples are as follows:

  • \0: Useful display space mark.
  • \: used to represent a backslash
  • \t: Use 杢 to represent tab characters.
  • \n: Use 杢 to represent a newline character.
  • \r: Use 杢 to represent the carriage return character.
  • ': Use 杢 to represent a single quotation mark
  • ": Use 杢 to represent double quotation marks.
  • \u{}: Create characters with Unicode codes.
    Among them, \u{} is used to create characters through Unicode codes, just fill in the Unicode codes in curly brackets, the example is as follows: //Use Unicode codes to create characters, the character represented by Unicode is 21! "\u
    { twenty one}"

Common Methods in String Type

The String type of the Swift language encapsulates many practical properties and methods, such as string inspection, character addition, insertion, and deletion operations, and character count statistics. Proficient use of these attributes and methods can enable developers to handle data with ease in programming.
As mentioned earlier, the value of a string variable is an empty string and the value of a string variable is empty are two different concepts. The instance of the String type uses the isEmpty method to determine whether the value of the string is an empty string

var obj1 = ""
if obj1.isEmpty {
    
    
    print("字符串为空字符串")
}

There is another way to judge whether a string variable is an empty string, that is, when the number of characters in the string variable is 0, the string can also be considered as an empty string, that is, through the count attribute of the string Determine whether the number of characters in it is 0

var obj1 = ""
if obj1.count == 0 {
    
    
    print("字符串为空字符串")
}

In addition to using "+" to directly concatenate String type instances, you can also use comparison operators

var com1 = "30a"
var com2 = "31a"
if com1 == com2 {
    
    
    print("com1 = com2")
}
if com1 < com2 {
    
    
    print("com1 < com2")
}

insert image description here
When comparing the size of two strings, the size of the characters will be compared one by one until an unequal character is encountered. The above sample code can be understood as follows: first compare the first character of the com1 string and com2 string, if they are equal, then compare the second character, and so on. Since com2's 4th character (2) is greater than com1's 4th character (1), the com2 string is larger than the com1 string.

var string = "Hello - Swift"

var startIndex = string.startIndex

var endIndex = string.endIndex

print(string)
print(startIndex)
print(endIndex)

var char = string[string.index(after: startIndex)]

var char2 = string[string.index(before: string.endIndex)]

print(char)
print(char2)

insert image description here
It should be noted here that the values ​​obtained by startIndex and endIndex are of the Index type, not integer types. They cannot be directly added or subtracted, and the corresponding method needs to be used to move the subscript. The index(after:) method is used to obtain the current subscript
. The next subscript, the index(before:) method is used to obtain the previous subscript of the current subscript. You can also intercept a certain substring in the string by passing in the subscript range


var string = "Hello - Swift"
var startIndex = string.startIndex

var endIndex = string.endIndex

var subString = string[startIndex...string.index(startIndex, offsetBy: 4)]
var subString2 = string[string.index(endIndex, offsetBy: -5)..<endIndex]

print(string)
print(startIndex)
print(endIndex)
print(subString)
print(subString2)

insert image description here
In the sample code above, "..." is a range operator, which will be introduced in detail in the following chapters. The offsetBy parameter is passed in the number of digits to move the subscript. If a positive number is passed to it, the subscript will move backward The corresponding number of digits. If a negative number is passed into it, the subscript will move forward by the corresponding number of digits. It is very convenient to use this method to intercept strings. The String type also encapsulates some methods, which can help developers conveniently perform operations such as appending, inserting, replacing, and deleting strings. Examples are as follows

var string = "Hello - Swift"
//获取某个子串在父串中的范围
var range = string.range(of: "Hello")
//追加一个字符,此时 string = "Hello-Swfit!"
string.append(Character("!"))
//追加字符串操作,此时string = "Hello-Swift! Hello-World"
string.append(" Hello-World")
//在指定位置插入一个字符,此时string = "Hello-Swift!~ Hello-World"
string.insert("~", at: string.index(string.startIndex, offsetBy: 12))
//在指定位置插入一组字符,此时string = "Hello-Swift!~~~~ Hello-World"
string.insert(contentsOf: ["~","~","~"], at: string.index(string.startIndex,
offsetBy: 12))
//在指定范围替换一个字符串,此时string = "Hi-Swift!~~~~ Hello-World"
string.replaceSubrange(string.startIndex...string.index(string.startIndex,
offsetBy: 4), with: "Hi")
//在指定位置删除一个字符,此时string = "Hi-Swift!~~~~ Hello-Worl"
string.remove(at: string.index(before:string.endIndex)) //删除指定范围的字符,此时string = "Swift!~~~~ Hello-Worl"
string.removeSubrange(string.startIndex...string.index(string.startIndex, offsetBy: 2))
//删除所有字符,此时string = ""
string.removeAll()
var string2 = "My name is Jaki"
print(string2)
//全部转换为大写
string2 = string2.uppercased()
print(string2)
//全部转换为小写
string2 = string2.lowercased()
print(string2)

insert image description here

//检查字符串是否有 My 前缀
string2.hasPrefix("My")
//检查字符串是否有 jaki 后缀
string2.hasSuffix("jaki")

collection type

There are three collection types provided in Swift language: array (Array), collection (Set) and dictionary (Dictionary). The array type is an ordered collection, and the data put into it has a number, and the number starts from 0 and increases sequentially. Through the number, developers can find the corresponding value in the Array array. A collection is a set of unordered data, and the data stored in it has no number. Developers can use the traversal method to obtain all the data in it. A collection is a key-value mapping structure, in which each stored value must correspond to a specific key, and the key cannot be repeated. Developers can directly obtain the corresponding value through the key. An example picture in Swift's official development documentation can clearly describe the similarities and differences of these three collection typesinsert image description here

Array (Array) type

The elements that can be stored in the array are not just numbers, it can store any type of data, but all data types must be unified. In actual development, the type of elements in the array determines the type of the array

//Int整形数组
var array1 : [Int]
var array2 : Array<Int>

The above two lines of code both declare an instance of an array of type Int. There are two ways to create an array. One is to use the constructor method of the array to create it, and the other is to use square brackets to create it quickly.

var array1 : [Int]
var array2 : Array<Int>
//创建空数组
array1 = []
array2 = Array()
//创建整形数组
array1 = [1, 2, 3]
//通过一组元素创建数组
array2 = Array(arrayLiteral: 1, 2, 3)

Similar to the String type, an empty array does not mean that the variable is nil, but that the elements in the array are empty. In Swift, only variables of the Optional type can be nil.

In the Swift language, arrays are implemented using structures. For arrays with a large number of repeated elements, developers can directly use shortcut methods to create

//创建大量有相同元素的数组
//创建有10个String类型元素的数组,并且每个元素都为字符串“Hello”
var array3 = [String](repeating: "Hello", count: 10)
print(array3)
//创建有10个Int类型元素的数组,并且每个元素都是1
var array4 = Array(repeating: 1, count: 10)
print(array4)

insert image description here
Readers should note that the type of the array must be specified when it is declared, but the developer does not necessarily need to specify the type explicitly. If the initial value is also set when the array is declared, the compiler will automatically infer the value of the array based on the assignment type. Type
Array The addition operator is also overloaded in the array. Developers can use "+" to add two arrays. The result of the addition is to splice the elements in the second array to the back of the first array. It should be noted that the added array types must be the same

var array5 = [1, 2, 3] + [4, 5, 6]
print(array5)

The array provides many methods for developers to obtain the relevant information of the array instance or to add, delete, modify, and check the array

print(array.count)
if array.isEmpty {
    
    
    print("array为空数组")
}
var a = array[0]
print(a)
var subArray = array[0...3]
print(subArray)
var b = array.first
print(b)
var c = array.last
print(c)
array[0] = 0
print(array)
array[0...3] = [1, 2, 3, 4]
print(array)
array.append(10)
print(array)
array.append(contentsOf: [11, 12, 13])
print(array)
array.insert(0, at: 0)
print(array)
array.insert(contentsOf: [-2, -1], at: 0)
print(array)
array.remove(at: 1)
print(array)
array.removeFirst()
print(array)
array.removeLast()
print(array)
array.removeFirst(2)
print(array)
array.removeLast(2)
print(array)
array.removeSubrange(0...2)
print(array)
array.replaceSubrange(0...2, with: [0, 1])
print(array)
array.removeAll()
print(array)
if array.contains(1) {
    
    
    print(true)
}
print(array)

insert image description here
It should be noted here that only when the array instance is a variable, methods such as adding, deleting, and modifying can be used, and operations related to modification cannot be performed on constant arrays.

//Int型数组
let arrayLet = [0, 1, 2, 3, 4]
//(Int, Int)型数组
let arrayLet2 = [(1, 2), (2, 3), (3, 4)]
//直接遍历数组
for item in arrayLet {
    
    
    print(item)
}
//进行数组枚举遍历
for item in arrayLet.enumerated() {
    
    
    print(item)
}
//进行数组角标遍历
for index in arrayLet2.indices {
    
    
    print(arrayLet2[index], separator:"")
}

insert image description here
Array instances can be traversed directly. There are still some differences between the for-in structure in Swift and the for-in structure in Objective-C. The for-in structure in Swift will traverse in order when traversing the array. There is also an enumerated() method in the array instance, which returns a set of tuples, and returns the subscript and corresponding elements of the array. Developers can also obtain the elements in the array by traversing the subscripts of the array. Unlike the String type, the subscripts in the array can be of the Int type, while the subscripts in the String are strictly of the Index type. Note here, Don't get confused.

There is an indices attribute in the array type, which will return a range (Range), which is the range of the array subscript.
The array type also provides a sorting function. If the elements in the array are integer data, you can use the sorted(by:) method provided by the system to perform the sorting operation. If it is some custom type, the developer can also set the The sorted(by:) method passes in the closure parameter to implement a new sorting rule, which will be described in detail in the following chapters. The sample code for the method of sorting the array is as follows:

var arraySort = [1, 3, 5, 6, 7]
arraySort = arraySort.sorted(by: >)
print(arraySort)
arraySort = arraySort.sorted(by: <)
print(arraySort)

print(arraySort.max())
print(arraySort.min())

insert image description here

Collection (Set) type

The collection type does not pay attention to the order of elements, but the elements in it cannot be repeated, and readers can also understand it as an unordered collection. Like an array, a collection must specify its type when declaring it, or assign an initial value to it, so that the compiler can infer the type of the collection by itself

var set1 : Set<Int> = [1, 2, 3, 4]
var set2 = Set(arrayLiteral: 1, 2, 3, 4)
var a = set1[set1.startIndex]
var b = set1[set1.index(after: set1.startIndex)]
var c = set1[set1.index(set1.startIndex, offsetBy: 3)]
print(a, b, c)

insert image description here
Since the collection does not pay attention to the order of the elements in it, it is not meaningful for the collection to get the value by subscript, but the collection type still supports the subscript to obtain the elements in it. It should be noted that the subscript operation of the collection is
irreversible The operation can only move backward, not forward.
The following method can get some information in the collection instance


//获取元素个数
set1.count
//判断集合是否为空集合
if set1.isEmpty {
    
    
print("集合为空") }
//判断集合中是否包含某个元素
if set1.contains(1){
    
    
print("集合包含") }
//获取集合中的最大值
set1.max()
//获取集合中的最小值
set1.min()

Collections also support addition, deletion, modification, and query operations

//向集合中插入一个元素
set1.insert(5)
//移除集合中的某个元素
set1.remove(1)
//移除集合中的第一个元素
set1.removeFirst() //移除集合中某个位置的元素
set1.remove(at: set1.firstIndex(of: 3)!)
//移除集合中所有的元素
set1.removeAll()

When using the remove(at:) method to delete an element at a certain position in the collection, it is necessary to pass in the subscript value of a collection element, and the subscript value of a specific element can be obtained through the firstIndex(of:) method of the collection instance. It should be noted that this method will return an optional value of the Optional type, because the element to be found may not exist, and the developer needs to unpack it when using it.
In addition to the difference between ordered and unordered sets and arrays, sets also have a unique feature: they can perform mathematical operations, such as intersection operations, union operations, and complement operations. A picture in Swift's official development document shows the scene when the set performs mathematical operations. insert image description here
It can be seen that the set supports four types of mathematical operations, namely intersection (intersection) operation, symmetricDifference (complement of intersection) operation, union (union) ) operation and subtracting (complement set) operation. The result of the intersection operation is the intersection of two sets. The result of the complement operation of the intersection is the union of the a set and the b set except the intersection of the a set and the b set. The result of the union operation is the union of the two sets. The result of the set operation is set a minus the intersection of set a and set b. The sample codes for the above four operations are as follows:

var set3:Set<Int> = [1,2,3,4]
var set4:Set<Int> = [1,2,5,6] //返回交集 {1,2}
var setInter = set3.intersection(set4) //返回交集的补集{3,4,5,6}
var setEx = set3.symmetricDifference(set4) //返回并集{1,2,3,4,5,6}
var setUni = set3.union(set4) //返回第二个集合的补集{3,4}
var setSub = set3.subtracting(set4)

Use the comparison operator "==" to compare whether two collections are equal. When all elements in the two collections are equal, the two collections are equal. The collection also provides some methods for judging the relationship between collections

var set5:Set = [1,2]
var set6:Set = [2,3]
var set7:Set = [1,2,3]
var set8:Set = [1,2,3]
//判断是否是某个集合的子集,set5 是 set7 的子集,返回 ture 
set5.isSubset(of: set7)
//判断是否是某个集合的超集,set7 是 set5 的超集,返回 ture 
set7.isSuperset(of: set5)
//判断是否是某个集合的真子集,set5 是 set7 的真子集,返回 ture 
set5.isStrictSubset(of: set7) //判断是否是某个集合的真超集,set7 不是 set8 的真超集,返回 false 
set7.isStrictSuperset(of: set8)

Similar to an array, a collection can also obtain all the data in the collection through for-in traversal. It can be traversed in three ways: traversing elements, enumeration of traversing collections, and subscripts of traversing collections. Set enumeration will return a tuple, in which the set subscript and its corresponding value are returned together

//遍历元素
for item in set7 {
    
    
	print(item) 
}
//遍历集合的枚举
for item in set7.enumerated() {
    
    
	print(item) 
}
//遍历集合的下标
for index in set7.indices {
    
    
	print(set7[index]) 
}

Although the collection does not emphasize the order of elements, when traversing, developers can sort them before traversing

for item in set7.sorted(by: >) {
    
    
	print(item) 
}

Dictionary (Dictionary) type

When a dictionary is used, a result is found by an index.
This data storage mode is called a key-value mapping mode, that is, a certain value can be found through a certain key.

//声明字典[param1:param2],这种结构用于表示字典类型,param1 为键类型,param2 为值类型 
var dic1:[Int:String]
//这种方式和[:]效果一样,dic2 与 dic1 为相同的类型
var dic2:Dictionary<Int,String>
//字典创建与赋值
dic1 = [1:"1",2:"2",3:"3"]
dic2 = Dictionary(dictionaryLiteral: (1,"1"),(2,"2"),(3,"3")) //在创建字典时,也可以不显式声明字典的类型,可以通过赋初值的方式来使编译器自动推断 
var dic3 = ["1":"one"]
//创建空字典
var dic4:[Int:Int] = [:]
var dic5:Dictionary<Int,Int> = Dictionary()

Dictionaries use keys to find specific values. Values ​​can be repeated in a dictionary, but keys must be unique. This ensures that a certain key can find a certain value, and if the developer creates duplicate keys in the dictionary, the compiler will also report an error.
The dictionary type also supports the use of isEmpty and count to determine whether it is empty and obtain the number of elements

//获取字典中的元素个数 
dic1.count 
//判断字典是否为空
if dic4.isEmpty{
    
    
	print("字典为空") 
}

The value corresponding to the modification can be obtained through a specific key


//通过键操作值 //获取值
dic1[2]
//修改值 
dic1[1]="0" 
//添加一对新的键值 
dic1[4] = "4"

The dic1[1]="0" and dic1[4]="4" in the above code actually complete the same operation, which can be understood as follows: When assigning a value to a key, if the key exists, it will be The update of the value, if the key does not exist, a new pair of key and value will be added. However, in development, in many cases, it is necessary to update an existing key. If the key does not exist, no new key-value pair will be added. To achieve this effect, you can use the update key-value method of the dictionary

//对键值进行更新 
dic1.updateValue("1", forKey: 1)

The updateValue(value:forkey:) method is used to update an existing key-value pair, where the first parameter is the new value, and the second parameter is the key to be updated. This method will return a value of type Optional when executed. If the key exists in the dictionary, the update will be successful, and the old value of the key will be wrapped into an Optional value and returned. If the key does not exist, nil will be returned. In development, the if-let structure is often used to handle

if let oldValue = dic1.updateValue("One", forKey: 1) {
    
     print("Old Value is \(oldValue)")
}

In fact, when the value in the dictionary is obtained through the key, an Optional value is also returned. If the key does not exist, the Optional value is nil, so the if-let structure can also be used to ensure the security of the program.

//通过键获取的数据也将返回Optional类型的值,也可以使用
if let if let value = dic2[1] {
    
    
print("The Value is \(value)") }
下面的方法可以实现对字典中键值对的删除操作:
//通过键删除某个键值对 
dic1.removeValue(forKey: 1) 
//删除所有键值对 
dic1.removeAll()

When traversing a dictionary, you can traverse the collection of all keys in the dictionary, or you can traverse the collection of all values ​​in the dictionary. You can get all the keys and all the values ​​​​of the dictionary through the keys attribute and values ​​attribute of the dictionary instance.

//通过键来遍历字典
for item in dic2.keys {
    
    
	print(item) 
}
//通过值来遍历字典
for item in dic2.values {
    
    
	print(item) 
}
//直接遍历字典
for item in dic2 {
    
    
	print(item) 
}
for (key,value) in dic2 {
    
     
	print("\(key):\(value)")
}

You can also directly traverse the dictionary instance, and the key and value of a tuple type wrapping dictionary will be returned during the traversal.
When traversing dictionary keys or values, it also supports sorting traversal

for item in dic2.keys.dic2.keys.sorted(by: >) {
    
     print(dic2[item]!)
}

Basic Operators and Program Flow Control

  • Unary operator: A unary operator acts on an operand, which can appear in front of the operand, such as the positive and negative operators "+" and "-", and the logical NOT operator "!".
  • Binary operators: Binary operators act between two operands, such as addition and subtraction operators "+" and "-".
  • Ternary operator: The ternary operator acts on three operands. The classic ternary operators include question mark and y-mark operators, which
    can easily realize simple judgment and selection structures.
//字符串赋值
var str = "Hello, playground" //整型赋值
var count = 5
//元组赋值
var group = (1,2,"12")
//Bool 赋值
var bol = true

If you want to assign the values ​​in a tuple to the specified value in turn, Swift also supports the use of destructuring assignment syntax for assignment

Assignment operators are used to pass values, and the result is that the quantity is assigned a specific value. Equality operators are used for comparison operations, which return a logical value of type Bool
Since the Swift language version 2.2, the auto-increment operator "++" and the auto-decrement operator "–" have been deleted.
These two operators cannot be used in the current version of the Swift language.

null coalescing operator

The optional value type is a unique feature of the Swift language, and the null coalescing operator is an operator designed for the optional value type

var q:Int? = 8 
var value:Int 
if q != nil {
    
    
	value = q! 
} else {
    
    
	value = 0 
}

The above example is a simple if-else selection structure. Using the conditional operator (ternary operator) introduced in Section 4.1.5, the above code can be abbreviated as follows


var q:Int? = 8
var value:Int
value = (q != nil) ? (q!) : 0

The code rewritten using the conditional operator is much simpler. The Swift language also provides a null coalescing operator to more concisely handle the conditional selection structure of this Optional type value. The null coalescing operator is represented by "??", and the above code can be rewritten as follows:

//空合并运算符 
var q:Int? = 8 
var value:Int value = q ?? 0

The null coalescing operator "??" is a binary operator, and the code rewritten using the null coalescing operator is more concise. It requires two operands. The first operand must be an Optional value. If the Optional value is not nil, it will be unpacked and used as the result of the null coalescing operation. If the value of this Optional is nil, the second operand is returned as the result of the null-coalescing operation. It is convenient to use the null coalescing operator to handle selection logic about Optional values

interval operator

In addition to supporting the Range structure to describe the range, Swift also provides an interval operator to express the range interval quickly and intuitively.

//创建范围 >=0 且<=10 的闭区间 
var range1 = 0...10 
//创建范围>=0 且<10 的半开区间 
var range2 = 0..<10

You can also use the "~=" operator to check if a number is contained in a range

//8 是否在 range1 中
print(range1 ~= 8) //输出 true

Interval operators are commonly used in for-in loop structures. Developers often use interval operators to define the number of loops. Examples are as follows:

//a...b 为闭区间写法 
for index in 0...3 {
    
    
	print(index) 
}
//a..<b 为左闭右开区间 
for index in 0..<3 {
    
    
	print(index) 
}

In the for-in loop structure, if the in keyword is followed by a collection, the variable index will automatically obtain the elements in the collection; if the in keyword is followed by a range, the index obtained is traversed from left to right The number of range indices to reach.

loop structure

for-in loop structure

Readers are no strangers to the for-in structure, and many of the contents introduced in the previous chapters use the for-in structure for demonstration. If the reader understands the C/Objective-C language, it should be noted here that the for-in loop structure is also supported in the C/Objective-C language, but it is called fast traversal, and the loop operations performed with it are out of order . The for-in structure in the Swift language is much more powerful, it can perform unordered loop traversal, and can also perform ordered loop traversal

//将打印 1,2,3,4,5 
for index in 1...5 {
    
    
print(index) }

The for-in structure requires two parameters. The second parameter can be an instance of a collection type or a range interval. The first parameter is a capture parameter. The elements traversed from the second parameter each time are will be assigned to it, and developers can use it directly in the loop structure.
When performing for-in loop traversal, developers do not need to capture the traversed values, and can use anonymous parameters to receive them. Swift uses the "_" symbol to represent anonymous parameters.

//如果不需要获取循环中的循环次序,可以使用如下方式 var sum=0;
for _ in 1...3 {
    
    
sum += 1 }

The traversal of collections is one of the commonly used scenarios of for-in loops, which have been introduced in detail in the previous chapters explaining collection types

//遍历集合类型
var collection1:Array = [1,2,3,4]
var collection2:Dictionary = [1:1,2:2,3:4,4:4] var collection3:Set = [1,2,3,4]
for obj in collection1 {
    
    
print(obj) }
for (key , value) in collection2 {
    
     print(key,value)
}
for obj in collection3 {
    
    
print(obj) }

while and repeat-while conditional loop structure

The while and repeat-while structures are also supported in the C/Objective-C language, and the functions are basically the same, but the Swift language changes the do-while structure to repeat-while.
In development, there is often a need for conditional circulation, such as simulating the process of storing water in a pool, storing 1/10 of the water each time, and stopping the water storage when it is full. The while loop structure can be very convenient to create this kind of loop code

var i=0
//当 i 不小于 10 时跳出循环 while i<10 {
    
    
print("while",i) //进行 i 的自增加 i+=1
}

In the while loop structure, after the while keyword, you need to fill in a logical value or an expression with a logical value as the result of the loop condition. If the logical value is true, the program will enter the body of the while loop. After the code of the loop body is executed, the loop condition is judged. If the loop condition is still true, the loop body will be entered again, otherwise the loop ends. Since the while loop judges whether to enter the loop body based on the loop condition, if the loop condition is always true, it will loop infinitely. Therefore, when using the while loop, developers should pay attention to modify the loop condition in the loop body, and modify The result is that the loop condition does not hold, otherwise an infinite loop will occur.

//使用 Switch 语句进行元组的匹配 
var tuple = (0,0)
switch tuple {
    
     //进行完全匹配
case (0,1): 
	print("Sure")
//进行选择性匹配 
case (_,1):
	print("Sim")
//进行元组元素的范围匹配 
case(0...3,0...3):
	print("SIM") 
default:
	print("") }

As shown in the above code, there are 3 ways to choose when matching tuples: the first way is exact match, that is, all elements in the tuple must be completely equal before the match is successful; the second way is Optional matching, that is, the developer only needs to specify some elements in the tuple for matching, and the elements that do not need to be concerned can be replaced by anonymous parameter identifiers. In this way, as long as the specified parameters are equal, the matching is successful; the third The first method is range matching, that is, the range specified by the corresponding position contains the value of the corresponding position of the tuple to be matched, even if the match is successful. The second matching method can be combined with the third matching method.
The case clause in the Swift language can also capture the parameters of the switch tuple, and the captured parameters can be directly used in the corresponding case code block. This is in the development The code written can be simplified in

var tuple = (1,0) //进行数据绑定

switch tuple {
    
    
//对元组中的第一个元素进行捕获
case (let a,1):
    print(a)
case (let b,0):
    print(b)
//捕获元组中的两个元素,let(a,b) 与 (let a,let b)意义相同
case let(a,b):
    print(a,b)
default:
    print("")
    
}

Readers here need to pay attention that the elements to be captured cannot play a matching role. For example, there are two elements in the tuple. If the case condition is (let a, 1), the second element in the tuple will be matched when matching parameter, if the match is successful, the value of the first parameter of the tuple will be passed to the constant a, and the code block in this case will be executed. In this code block, the developer can directly use the constant a. Therefore, the element to be captured actually acts as an anonymous identifier when matching, such as the third case clause in the above code, its condition is let(a,b), in fact, this condition will always be matched successfully . Moreover, if the developer captures all the elements in the tuple, in terms of code performance, it can be written as (let a, let b), or it can directly capture the entire tuple as let(a, b). The two ways are only different in writing, and there is no difference in use.


var tuple = (0,0) //进行数据绑定
//对于进行了数据捕获的 Switch-case 结构,可以使用 where 关键字来进行条件判断
switch tuple {
    
    
    case (let a,1):
        print(a)
//当元组中的两个元素都等于 0 时才匹配成功,并且捕获第一个元素的值
    case (let b,0) where b==0:
        print(b) //当元组中的两个元素相同时,才会进入下面的case
    case let(a,b) where a==b:
        print(a,b)
    default:
        print("")
}

Flow jump statement in Swift language

The jump statement can interrupt the loop structure in advance, and can also artificially control the jump of the selected structure, making the execution of the code more flexible and changeable. Swift provides a large number of process jump statements for developers to use. Familiarity with the structure and characteristics of these statements can greatly improve development efficiency. The flow jump statements provided in Swift mainly include continue, break, fallthrough, return, throw, and guard
continue statements used in the loop structure, whose function is to skip this loop and start the next loop directly. It should be noted here that the function of continue is not to jump out of the loop structure, but to skip this loop and directly execute the next cycle


for index in 0...9 {
    
    
    if index == 6 {
    
    
        continue
    }
    print("第\(index)次循环")
}

insert image description here
The default operation scope of the continue statement directly includes its loop structure. If there are multiple layers of loop structures nested in the code, the continue statement will skip this loop. So, if you want to skip this loop, but jump directly to the layer of loop structure specified by the developer

MyLabel:for indexI in 0...2 {
    
    
    for indexJ in 0...2 {
    
    
        if indexI == 1 {
    
    
            continue MyLabel
        }
    print("第\(indexI)\(indexJ)次循环")
    }
}

insert image description here
The above code creates a two-layer loop structure. The continue statement is used in the inner loop to jump, MyLabel is the label of the outer loop, so the continue jump here will jump out of the outer loop when indexI is equal to 1, and start directly Loop operation with indexI equal to 2.

The break statement is an interrupt statement, which can also be used in a loop structure. Unlike the continue statement, the break statement will directly interrupt the loop structure directly containing it, that is, when the loop structure is one layer, if the loop has not been executed, Then all subsequent loops will be skipped. If there are multiple layers of loop structure, the program will directly interrupt the loop structure directly containing it, and continue to execute the loop structure outside the loop structure

for index in 0...9 {
    
    
    if index == 6 {
    
    
        break
    }
    print("第\(index)次循环")
}

insert image description here
The above code uses a break statement to interrupt when the index is equal to 6, and all printing information after the fifth cycle will be skipped. The break statement will break the loop structure that directly contains it by default, and you can also use the specified label to break the specified loop structure

MyLabel:for indexI in 0...2 {
    
    
    for indexJ in 0...2 {
    
    
        if indexI == 1 {
    
    
            break MyLabel
        }
    print("第\(indexI)\(indexJ)次循环")  
    }
}

insert image description here
The break statement can also be used in the switch structure. In the switch structure, the break statement will directly interrupt all subsequent matching processes and directly jump out of the switch structure. In the Swift language, the switch-case selection matching structure defaults to the break operation, so developers do not need to manually add the break code. The fallthrough statement
is a unique flow control statement in Swift. As mentioned earlier, when the switch-case in the Swift language After the structure matches a case, it will automatically interrupt the matching operation of all subsequent cases. If the switch-case structure does not automatically interrupt the operation in actual development, you can use the fallthrough statement


var tuple = (0,0)
switch tuple {
    
    
    case (0,0):
        print("Sure")
        //fallthrough 会继续执行下面的 case
        fallthrough
    case (_,0):
        print("Sim")
        fallthrough
    case(0...3,0...3):
        print("SIM")
    default:
        print("")
}

insert image description here
The return statement should be very familiar to the reader. It is used in a function to return a result value, and it can also be used to terminate a function that does not return a value type early. Of course, the application scenarios of the return statement are not limited to functions, and return can also be used in closures to return


//有返回值函数的返回
func myFunc()->Int{
    
    
    return 0
}
//无返回值函数的返回
func myFunc(){
    
    
    return
}

The throw statement is used to throw exceptions. If the exception thrown by the throw statement is not caught and processed, the program will also be interrupted.

//定义异常类型
enum MyError:Error{
    
    
    case errorOne
    case errorTwo
    
}
func newFunc() throws{
    
    
    //抛出异常
    throw MyError.errorOne
}

The guard-else structure statement is a new grammatical structure added after Swift 2.0. The Swift team created it to make the structure and logic of the code clearer. In actual development, especially in the writing of functions, such a scenario is often encountered: when the parameters meet a certain condition, the function can be executed normally, otherwise the execution of the function is terminated directly through return, if you do not use guard-else structure

Basic application of functions

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

Grammatical structure of closures

insert image description here

insert image description here

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/weixin_61196797/article/details/131109186