First, basic grammar

A semicolon

Swift does not require a semicolon at the end of each line; When multiple statements are written on the same line, they must be separated by a semicolon:

var str = "Hello, swift" print(str) let name = "Mars"; let age = 18; Copy the codeCopy the code

identifier

An identifier is a name given to a variable, constant, method, function, enumeration, struct, class, protocol, etc. The letters that constitute identifiers have certain norms. The naming rules of identifiers in Swift language are as follows:

  • Case sensitive,MynamewithmynameAre two different identifiers;
  • The identifier may start with an underscore_Or start with a letter, but not a number;
  • Other characters in the identifier can be underscores_, letters or numbers.

The letters in Swift are encoded in Unicode. Unicode is called Unicode, and it includes Asian characters like Chinese, Japanese, Korean, and even emoticons that we use in chat

Let 🐂 = 20 var 🐓 = "Chicken" copy codeCopy the code

If you must use a keyword as an identifier, you can add an accent (‘) before and after the keyword, for example:

Let 'class' = "asda" copy codeCopy the code

Swift, the blank space

Swift does not completely ignore whitespace like C/C++ and Java do. Swift has some requirements for whitespace, but it is not as strict as Python on indentation. In Swift, operators cannot be directly followed by variables or constants. For example, the following code returns an error:

Let a= 1+ 2 let b = 1+ 2 copy codeCopy the code

This is the only way to avoid errors:

let a = 1 + 2; // Let b = 3+4 // This can also copy codeCopy the code

A printout

Swift uses its own print function to print output:

Print ("Mars") // Print the Mars copy codeCopy the code

The print function is a global function, and the complete function signature is:

/// -parameters: /// -items: the parameter to print /// -separator: the separator (' "" ') is used by default. /// -terminator: Newline (' "\n"). Public func print(_ items: Any... Separator: String = "", terminator: String = "\n") copies the codeCopy the code

The print function takes three arguments, whose meanings are commented out in the code. The items argument is of type Any and can be passed in Any type. . Stands for variable arguments, more than one can be passed in. Such as:

Print ("1","2","3","4") // print 1, 2, 3, 4Copy the code

Separator is the separator, terminator is the separator, terminator is the newline \n. Separator is the separator, terminator is the separator, terminator is the terminator. Of course, pass in other arguments to change the default values, such as:

// Print ("123", separator:"", terminator:"") print(20) // Replace separator ("1","2","3", Separator :"+", terminator:"") // Prints 1+2+3 copy the codeCopy the code

The print function prints external variables using \() :

Let age = 18 print("age is \(age)"Copy the code

Second, the constant

In Swift, a constant, once set, cannot change its value while the program is running. So a constant can only be assigned once. Constants can be any data type such as integer constants, floating point constants, character constants, or string constants. There are also constants of enumerated type. #### constant declaration Swift defines constants using the let keyword.

Let constA = 42 copies the codeCopy the code

Type annotation

When declaring a constant or variable, a type annotation can be added to indicate the type of the value to be stored in the constant or variable. To add a type annotation, add a colon and a space after the constant or variable name, followed by the type name.

Let constB: Int = 32 let constC: Float = 3.1415 let constD: Int constD = 21 Copy the codeCopy the code

In the above example, constD is declared as Int, so it is permissible to then assign constD to 21. However, if the constant is declared with neither a value nor a type, an error is reported. For example, the following code is incorrect:

// Example of incorrect code let age age = 10 Copy codeCopy the code

Note that neither constants nor variables can be used until initialized. The value of a constant is not required to be determined at compile time, but must be assigned once before it can be used. For example the following constant age:

Func getAge() -> Int {return 20} let age = getAge() print(age) copy codeCopy the code

Constant named

Constants can be named by letters, numbers, and underscores. Constants need to start with a letter or underscore. Swift is a case sensitive language, so uppercase letters are not the same as lowercase letters.

Three, variables,

Variable declarations

Swift uses the var keyword to declare variables, as follows:

Var varB:Float varB = 3.14159 print(" PI is \(varB)")// Print PI is 3.14159Copy the code

Variable naming

Variable names can consist of letters, numbers, and underscores. Variable names need to start with a letter or underscore. Swift is a case sensitive language, so uppercase letters are not the same as lowercase letters. Variable names can also use simple Unicode characters, as in the following example:

4. Data types

Swift provides a very rich variety of data types. Here is a simple table to show the common data types in Swift:

Swift differs from other languages in that it provides only two broad categories of data types: value types and reference types. Value types include enumerations and structs. The basic data types such as Int and Bool that we commonly use in OC are structure types in SWIFT.

Int

Swift provides a special integer type Int, including Int8, Int16, Int32, Int64. The length is the same as the original character length of the current platform:

  • On 32-bit platforms,IntandInt32The length is the same.
  • On 64-bit platforms,IntandInt64The length is the same.

Int8, Int16, Int32, and Int64 are signed integers of 8, 16, 32, and 64 bits, respectively.

Unless you need an integer of a certain length, Int will generally suffice. This improves code consistency and reusability. Even on 32-bit platforms, the range of integers that an Int can store ranges from -2,147,483,648 to 2,147,483,647, which is large enough most of the time.

UInt

Swift also provides a special unsigned type UInt, including UInt8, UInt16, UInt32, and UInt64. The length is the same as the original character length of the current platform:

  • On 32-bit platforms,UIntandUInt32The length is the same.
  • On 64-bit platforms,UIntandUInt64The length is the same.

UInt8, UInt16, UInt32, and UInt64 Are unsigned integers of 8, 16, 32, and 64 bits respectively.

Note: Try not to use UInt unless you really need to store an unsigned integer of the same length as the current platform native. Except in this case, it is best to use Int, even if the value you want to store is known to be non-negative. The uniform use of ints improves code reusability, avoids conversions between different types of numbers, and matches type inference for numbers.

Floating point numbers: Float, Double

Floating point numbers are numbers that have a fractional part, such as 3.14159, 0.1, and -273.15.

Floating-point types represent a larger range than integers and can store larger or smaller numbers than ints. Swift provides two types of signed floating point numbers:

  • Double represents a 64-bit floating point number. High accuracy, at least 15 digits. Use this type when you need to store very large or high precision floating point numbers.
  • Float represents a 32-bit floating point number. The precision is only 6 digits. You can use this type if the precision is not high.

To define data of type Double, we simply assign a decimal. To define data of type Float, we declare the type:

Let letDouble = 3.12 // Double let letFloat: Float = 3.31 // Float copy codeCopy the code

Boolean value: Bool

Swift has a basic Boolean type called Bool. Boolean values refer to logical values because they can only be true or false. Swift has two Boolean constants, true and false.

5. Literals

A literal is a value such as a particular number, string, or Boolean that can directly indicate its type and assign a value to a variable. Such as:

Let aNumber = 3 // Integer literals let aString = "Hello" // string literals let aBool = true // Boolean literals copy codeCopy the code

Integer literals

An integer literal can be a decimal, binary, octal, or hexadecimal constant. The binary prefix is 0b, the octal prefix is 0o, the hexadecimal prefix is 0x, and the decimal prefix has no prefix:

Let decimalInteger = 17 // 17 - Decimal let binaryInteger = 0b10001 // 17-0B, binary let octalInteger = 0O21 // 17-0O, Octal let hexadecimalInteger = 0x11 // start with 17-0x, copy the code in hexadecimalCopy the code

Floating point literals

Floating-point literals have integer, decimal, decimal, and exponential parts. Unless specified, the default derived type for floating-point literals is Double in the Swift library type, which represents a 64-bit floating-point number. Floating-point literals are expressed in decimal by default (without a prefix) or hexadecimal (prefixed with 0x).

Let doubleDecimal1 = 125.0 // decimal equivalent to 1.25e2 that is 1.25e 10^2 Let doubleDecimal2 = 0.0125 // decimal E/e Equivalent to 1.25e-2 that is 1.25e/e 10^-2 let doubleHexadecimall1= 0xFp2 // in hexadecimal, 0xFp2 means 15 e ^2, That is, 60.0 in decimal let doubleHexadecimall2= 0xfP-2 // in hexadecimal, 0xfP-2 means 15 e ^ 2 or 3.75 copy codeCopy the code

Another example is 12.1875:

Let decimalDouble = 12.1875 // Decimal float literal let exponentDouble = 1.21875E1 // Decimal float literal let hexadecimalDouble = 0xC. 3P0 // Copy code for hexadecimal floating-point literalsCopy the code

Floating-point literals allow the use of underscores (_) to enhance the readability of numbers. Underscores are ignored by the system and therefore do not affect the literal value. Similarly, it is possible to prefix a number with 0 without affecting the literal value. Such as:

Let a = 1_000_000 // 1000000 let b = 000123456 //123456 Copy codeCopy the code

String literals

A string literal consists of a string of characters enclosed in double quotes and is of the following form:

Let name = "Mars" copy codeCopy the code

Note that Character literals need to be typed, because Character literals also use double quotes, so they need to be declared to distinguish them from string lines:

Let char: Character = "a" copy codeCopy the code

Type conversion

In Swift, integers and floating-point numbers cannot be directly computed, and data type conversion is required:

Let intA = 3 let doubleB = 0.14159 let PI = Double(intA) + doubleB let intPi = Int(PI) copy codeCopy the code

In this example, intA is an integer, doubleB is a floating-point number, and different types cannot be added directly. The result PI is a floating point. It is also possible to force PI to Int directly using the Int keyword.

Of course, numeric literals can be added directly because there is no explicit type of their own:

Let result = 3 + 0.14159 Copy codeCopy the code

6. Tuples

A tuple is a compound type in Swift that can combine multiple types of data. Such as:

Let http404Error = (404, "Not Found") print("The status code is \(http404Error.0)") // Print The status code is 404Copy the code

The constant http404Error in this example is of type (Int, String). Http404Error: const http404Error:

Print (http404Error.0) // print(http404Error.1) // Print Not Found copy codeCopy the code

We can also use a tuple to receive a defined tuple type constant http404Error:

let (statusCode, StatusMessage) = http404Error print("The status code is \(statusCode)") // Print The status code is 404 copy codeCopy the code

If you want to receive only certain parts of the data, use _ instead:

Let (justTheStatusCode, _) = http404Error // Only Int data copy code from http404Error was receivedCopy the code

When you define a tuple type variable, you can also specify a tag for the value. Tag name +: is used to obtain the value:

let http200Status = (statusCode: 200, description: "Success ") print("The status code is \(http200statuscode)") // Print The status code is 200Copy the code

Seven, the if – else

In Swift, the condition after the if can omit the brace, but the brace cannot be omitted. The condition must be a Bool.

let grade = 99 if grade >= 90 { print("Grade is A") }else if grade >= 80 { print("Grade is B") }else if grade >= 70 { Print ("Grade is C")}else {print("Grade is D")Copy the code

The use of the guard

1. Guard is a new syntax for Swift2.0

2. Very similar to the if statement, it is designed to improve the readability of programs

Guard statements must have an else statement, which has the following syntax:

3.1. Skip the else statement when the conditional expression is true and execute the statement group

3.2. Execute an else statement if the conditional expression is false. Jump statements are typically return,break,continue, and throw

  1. Do not use the guard

    import UIKit func isUserName(username : String){ if username ! = nil {if isPhoneNumber(username: username){if isUnicom(username: username){print(" )}else{print(" Mobile phone number is not Unicom number!" }}else{print(" username not phone number!" }}else{print(" Username is empty!" ) }} isUserName(username : "18600000000")Copy the code

The use of Guard

Func isUserNameGuard(username: String) -> Void{guard username! = nil else {print(" Username is empty!" ) return} guard isPhoneNumber(username: username) else {print(" username is not a phone number!" Return guard isUnicom(id: id) else {print(id: id) Return} print(" Mobile phone number is China Unicom number!" )}Copy the code

Eight, while

In Swift, the condition after the while can omit the brace, but the brace cannot be omitted.

Var num = 5 while num > 0 {print("num is \(num)") num -= 1} num is 5 num is 4 num is 3 num is 2 num is 1Copy the code

Note that num– is not used here because the increment ++ and decrement — operators were removed in Swift 3.0. Swift also provides a repeat – while statement, which is equivalent to a do – while statement in C:

Var num1 = -1 repeat {print("num is \(num1)")}while num > 0 // Print num is-1 duplicate codeCopy the code

9. For-in loop

Swift uses for-in loops to iterate over all the elements in a collection.

Var arr = [1, 2, 3, 4, 5] for index in arr {print(index)Copy the code

In this example, index is a constant by default and can be declared as a variable:

Var arr = [1,2,3,4,5] for var index in arr {print(index)Copy the code

If you don’t need index in the loop, you can use _ instead:

Var arr = [1,2,3,4,5] for _ in arr {print("hello")} // print hello hello hello hello hello copy codeCopy the code

Closed interval operators…

Closed interval operators represent ranges of values, for example:

a... B //a <= Value <= b Copies the codeCopy the code

The for-in loop example above can be written as:

for index in 1... 5 {print(index)} // print out 1, 2, 3, 4Copy the code

The half-open interval operator.. <

The half-open interval operator represents a range of values, for example:

a.. <b //a <= Value <b Copies the codeCopy the code

Apply to for-in loops:

for index in 1.. <5 {print(index)} // print out 1, 2, 3, 4 copy codeCopy the code

The interval operator applies to arrays

The interval operators described above can also be used on arrays to represent ranges of subscript values:

Var names = [" Tom ", "Jack "," Mars ", "Thomas "] for name in names[0...3] {print(name)} // Print Tom Jack Mars Thomas copy codeCopy the code

A range can also be specified using a single range:

/ /... Var names = [" Tom ", "Jack "," Mars ", "Thomas "] for name in names[...2] {print(name)} // Print Tom Jack Mars copy codeCopy the code

Use the half-open interval operator:

/ /.. <2 = 0 1 var names = [" Tom ", "Jack "," Mars ", "Thomas "] for name in names[..<2] {print(name)} // Print Tom Jack copy codeCopy the code

10 and the switch

The switch statement in Swift must be guaranteed to handle all cases. In switch statements, case and default cannot be followed by curly braces {}. The default is not to write break 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")} // Print the number is 1 copy codeCopy the code

You can use the fallthrough keyword to achieve the through-through effect (compound condition) :

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

Compound conditions

In addition to implementing compound conditions using the Fallthrough keyword, you can also write multiple conditions in conditions separated by commas. In addition, the switch also supports String and Character types:

let stri = "Mars" switch stri { case "Mars", "Tom": print("He is my friend") default: Break} // Print He is my friend copy codeCopy the code

Interval matching in switch

The interval operator can also be used in switch statements:

let count = 89 switch count { case 0: print("none") case 1.. <10: print("a few") case 10.. <100: print("a lot") default: print("many")} // Print a lot copy codeCopy the code

11, where

Filter criteria can be filtered using the WHERE keyword in Swift:

var numbers = [10, 20, -10, 30, -20] var sum = 0 for num in numbers where num > 0 {sum += num} print(sumCopy the code

In this example, where num > 0 filters out the positive numbers in the array and then loops to add them.

conclusion

Briefly learned some basic syntax of SWIFT