Hi, I’m Mars. With the official Xcode 11 update, we have made some simple attempts at the Swift UI, which is very powerful and requires further research. I learned Swift by myself in my spare time and tried to reconstruct our company’s online project. The study of Swift was later stalled because of the project’s schedule. With Swift 5, the ABI is more stable, and Apple introduced the Swift UI this year, so it’s time to take a good look at Swift. I will share and summarize the whole process of learning Swift through a series of articles in the future. I hope you can give me your support and attention. Article # grammar

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 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 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 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 the code

This is the only way to avoid errors:

leta = 1 + 2; // This is recommended by the coding specificationletB is equal to 3+4 // That's fineCopy the code

A printout

Swift uses its own print function to print output:

print("Mars") // Output MarsCopy the code

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

/// -parameters: /// -items: the parameter to be printed /// -separator: the separator (') is used by default""/// - terminator: line break (')"\n"`).
public func print(_ items: Any... , separator: String ="", terminator: String = "\n")
Copy 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") // Output 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:

// Undelimiter and newlineprint("123", separator:"", terminator:"")
print(20) // Prints 12320 // replaces the delimiterprint("1"."2"."3", separator:"+", terminator:"") // Prints 1+2+3Copy the code

The print function prints external variables using \() :

let age = 18
print("age is \(age)") // Prints age is 18Copy 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
Copy 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
letConstC: Float = 3.1415let constD: Int
constD = 21
Copy 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:

// Examples of incorrect codelet age
age = 10
Copy 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 {
    return20}let age = getAge()
print(age)
Copy 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 varA = 42
print42 var varB:Float varB = 3.14159print("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 typelet letFloat: Float = 3.31 // Type of FloatCopy 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:

letANumber = 3 // Integer literalslet aString = "Hello"// String literallet aBool = true// Boolean literalsCopy 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:

letDecimalInteger = 17 // 17 - Decimal notationletBinaryInteger = 0b10001 // 17-0B, binaryletOctalInteger = 0o21 // 17-0O, octalletHexadecimalInteger = 0x11 // Starting with 17-0x, 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).

letDoubleDecimal1 = 125.0 // E decimal, equivalent to 1.25e2 or 1.25e 10^2letDoubleDecimal2 = 0.0125 // Decimal, equivalent to 1.25E 2 or 1.25e 10^-2letDoubleHexadecimall1 = 0xFp2 // In hexadecimal, 0xFp2 means 15 e ^2, or 60.0 in decimalletDoubleHexadecimall2 = 0xfp-2 // In hexadecimal, 0xfP-2 means 15 e ^ 2, or 3.75Copy the code

Another example is 12.1875:

letDecimalDouble = 12.1875 // Decimal floating-point literalletExponentDouble = 1.21875E1 // Decimal floating-point literalletHexadecimalDouble = 0xc.3P0 // A hexadecimal floating point literalCopy 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 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 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 the code

Type conversion

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

let intA = 3
letDoubleB = 0.14159let pi = Double(intA) + doubleB
let intPi = Int(pi)
Copy 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:

letResult = 3 + 0.14159Copy 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) // Prints 404print(http404Error.1) // Prints Not FoundCopy 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 404Copy the code

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

let(justTheStatusCode, _) = http404Error // Only Int data 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 \(http200Status.statusCode)") // 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"} // Print Grade is ACopy 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)")}whileNum > 0 // Num IS-1 is displayedCopy 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} // Print out 1, 2, 3, 4, 5Copy 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} // Print out 1, 2, 3, 4, 5Copy 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 helloCopy the code

Closed interval operators…

Closed interval operators represent ranges of values, for example:

a... B //a <= Value <= bCopy the code

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

for index in1... 5 {print} // Print out 1, 2, 3, 4, 5Copy the code

The half-open interval operator.. <

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

a.. <b //a <= Value <bCopy the code

Apply to for-in loops:

for index in1.. < 5 {print} // Print out 1, 2, 3, 4Copy 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)} // Prints Tom Jack Mars ThomasCopy 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)} // Prints Tom Jack MarsCopy the code

Use the half-open interval operator:

/ /.. 1 Var names = ["tom"."jack"."mars"."thomas"]
for name in names[..<2] {
    print(name)} // Prints Tom JackCopy 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 number is 1Copy 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 friendCopy the code

Interval matching in switch

The interval operator can also be used in switch statements:

let count = 89
switch count {
caseZero:print("none")
case1.. The < 10:print("a few")
case10.. < 100:print("a lot")
default:
    print("many"} // Print a lotCopy 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(sum) // Prints 60Copy the code

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

conclusion

Simple learning of swift part of the basic grammar, today here, if there is wrong in the text can be pointed out by message. Welcome everyone to scan the code to follow the wechat public number, and exchange and learn together.

For more technical knowledge, please scan the code to follow the wechat public account

IOS advanced