Summary of Swift basic grammar learning

Summary of Swift basic grammar learning

1. Basics

1.1) Swift still uses // and /* */ for comments, and /* */ allows multi-line comments.

1.2) Swift uses print and println to print. Its parameter is a generic type, and almost all types are printable.

1.3) It is correct to put a semicolon after a statement in Swift or not, but the preferred style of Swift is not to put a semicolon at the end. If there are multiple statements, they must be separated by semicolons.

1.4) Underscores (_) in a number will be ignored, which is convenient for recognizing large numbers and can also be used to add zeros in front.

1.5) Swift does not allow addition, subtraction, multiplication and division between different types. You must first perform type conversion or operator overloading.

1.6) typealias can specify another name for a type, so that the meaning of the type can be clearly expressed. typealias newType = OldTypeName

1.7) assert asserts that an exception is thrown. The first parameter of assert indicates the condition that passes without throwing an exception. The second parameter indicates a prompt. The second parameter can be omitted.

1.8) The = assignment operator in Swift does not return a value, so you won’t make mistakes like if a = 3 {}. Add spaces before and after the operator to prevent Xcode from not recognizing it.

2. Variables

2.1) let defines constants, var defines variables. The initial value of let declaration must be specified when declaring, and the ordinary var declaration must also assign an initial value.

2.2) Variables declared with let cannot be changed, while variables declared with var can be changed, but you cannot declare a constant or variable that has already been declared.

2.3) You can declare multiple constants or variables on a single line, separated by commas; if each constant corresponds to a var or let, just separate them with semicolons.

2.4) Every constant and variable must have a fixed type. If the type is not specified, Swift will infer it based on the type of the value assigned later.

2.5) Swift names cannot use reserved words and arrows/cannot start with numbers. There are no other rules. You can even use dogs and cats to name them.

2.6) If you want to use keywords to name something, it is not allowed. However, you can add `` before and after the name, such as `let`. It is also OK to add `` to non-keyword names.

2.7) In Swift, you can declare a tuple, which is similar to (Int, String). You can declare it with var or let, and both of them will be variables or constants.

2.8) The tuple method is not much different from declaring two variables and constants separately. You can use the variables separately or as a tuple, or mix them together.

2.9) You can use the tuple name to directly access the corresponding value in the tuple through the subscript index, such as aaa.0 aaa.1

2.10) You can name the elements in a tuple, such as (code:404,message:"Not Found"), and then you can access them using aaa.code and aaa.message

3. Type

3.1) UInt8 and Int32 of int type can use min and max to get the maximum and minimum values

3.2) Double is a 64-bit floating point number, Float is a 32-bit floating point number, and decimals are automatically inferred to be of type Double unless the type is specified.

3.3) You can assign an integer value to a constant or variable that is specified as a floating point type, but not to an integer variable, as it will be automatically converted to a floating point number.

3.4) A variable or constant of a specified type cannot be assigned a value of a different type. It cannot be automatically converted, except for assigning an integer value to a floating point type.

3.5) Adding a ? after the specified type indicates an optional type, which means that it may not have a value of nil, and then you can use it through optional binding or check whether it is empty.

3.6) If it is an optional type of a class, you can access its properties and methods through ?. It is based on whether the former will respond to the latter method. If it can respond, it will be executed, otherwise it will return nil.

3.7) ? is actually a syntax sugar. For example, the String? type is equivalent to the Optional<String> type. It is just convenient for writing. It is essentially different from the String type.

3.8) If you don’t want to use the check whether it is empty or use optional binding or .? to access it, you can use the most direct and simple ! forced unpacking to use it, but the premise is that it can be guaranteed to be non-empty.

3.9) If an optional value has no value and you force unwrap it, an error will be reported. An optional type will be implicitly assigned to nil. You can also assign it to nil during use.

3.10) The reason why optional types are needed is that Swift is a type-safe language. It requires that you have a value when using a variable, but this optional type is too troublesome, so the ! type was created. The essence of the ! type should be an optional type.

3.11) Declare it as an optional type, and you don’t need to initialize it. It is equivalent to adding! to force unpacking every time you use the optional type. You don’t need to add! yourself. You need to ensure that it is not empty, otherwise it will fail to use

4. Strings

4.1) ... indicates a closed interval / ..< indicates an open interval, == indicates equal values ​​/ === indicates the same reference, + can directly add strings or arrays

4.2) String in Swift is a value type. When it is assigned to a constant variable or passed in a function, a value copy is made. Swift only makes a copy when necessary.

4.3) You can use for in to traverse the string, use the count global function to count the number of characters, use the isEmpty property to determine whether it is an empty string, and use hasPrefix to determine the prefix (suffix, etc.)

4.4) You can use startIndex and endIndex to get the start and end indexes, and use arrays and indexes to access single characters; you can also generate strings using \()

5. Arrays

5.1) Arrays in Swift can be declared using [String] and Array<String>. They have the same meaning and can be assigned directly using brackets []. The values ​​inside must be of the same type.

5.2) array has attributes such as count/isEmpty, and methods such as append/insert/remove. It can directly add an array. It can get values ​​through subscripts and subscript intervals. The interval gets an array.

5.3) for item in shoppingList / for (index, value) in enumerate(shoppingList) Two traversal methods, the latter will know the index

5.4) You can initialize an array using [Double](count: 3, repeatedValue: 3.3) / Array(count: 3, repeatedValue: 2.5)

5.5) Arrays are also passed by value. If array a is assigned to array b, a and b are two copies and modifications will not affect each other.

6. Dictionary

6.1) Dictionaries are declared using [String : String] / Dictionary<String, String> and are in the form of [a:b,c:d], accessing values ​​by key

6.2) You can add a key-value pair directly through a[b] = c, and add and delete key-value pairs through updateValue and removeValueForKey

6.3) You can use for (airportCode, airportName) in airports / for airportCode in airports.keys to iterate over key-value pairs or keys or values.

6.4) You can directly assign [:] to clear the dictionary. The key value can be Int. Like string and array, dictionary also copies the value.

7.Set

7.1) Declare a Set with Set<Int>, assign values ​​to it just like an array, and clear it by assigning []. It must also be of the same type, and has insert/contains methods and an isEmpty property

7.2) Set also has for in traversal, methods for taking the difference of two sets to do permutations, and methods for determining subsets and supersets, etc.

8. For Loop

8.1) The index in for index in 1...5 is only in the scope of the current loop. If there is an index outside the for loop, modifying it will not affect it.

8.2) for _ in 1...10 If you don't need the index of the loop, you can use an underscore _ to replace it. In Swift, you can usually use _ to replace any value you don't need.

8.3) for var index = 0; index < 3; ++index This for loop is still possible

9. Switch Statement

9.1) The switch in Swift must exhaustively enumerate all possibilities, otherwise a default must be added. When exhaustively enumerating, you can put multiple possible values ​​after a case, separated by commas.

9.2) Exhaustiveness can be an interval represented by ... and ..<. For tuples, one can use the _ wildcard and the other can match, or both can match, or both can be intervals (only one element can also be used for value binding)

9.3) When doing unified configuration, you can use var x/let x, or let (x,y) to bind values, where var declarations can be modified

9.4) When using let to bind a value, you can add a where clause to make a conditional judgment. Switch does not need to use break to prevent penetration, but it will still go to the next case to judge the condition. Using break can still jump out of the switch directly.

9.5) You can also use break/continue to jump out of a label in switch.

<<:  Experts say: This is an iOS development skill that you can’t miss (Part 2)

>>:  4 reasons why Microsoft can't give up its mobile operating system

Recommend

Firefox for Android is testing credit card and address autofill features

After switching to Fenix, Mozilla has added most ...

If you want to run a successful e-commerce event, start with these aspects!

So far, the author has been working in the fresh f...

How to create a hit product from 0 to 1?

In the current situation where paid content is ho...

Zhai Shanying: Find out the secrets of capital making money

Tutorial Introduction Companies that do not under...

Todd "Attraction Unlocked" Baidu Cloud Download

Introduction to the video tutorial of the pickup ...

14 problems and solutions for bidding promotion!

In bidding promotion , we often encounter some co...

Free Qianjiang Road March 2022 Courses

Free Qianjiang Road March 2022 course resources i...

Is the mosquito repellent song that is popular on the Internet really effective?

Summer is here, and it’s time to “fight mosquitoe...

Warcraft Movie: The Sunset of a Legendary IP

(Original title: Warcraft Movie: The Sunset of a ...