Swift knowledge (1), swift knowledge
Apple canceled the use of oc pointers and other insecure access, and discarded the smalltalk syntax, which was fully changed to the dot syntax, providing a canonical type overload similar to java;
First, let's take a look at the Swift language. Just like the C language, Swift uses variables for storage and uses variable names to associate values. Immutable variables are widely used in swift, which is also a constant. However, Swift is far more powerful than C constants. Remember, here we are talking about being more powerful than a C constant, not a C language. This should be understood clearly. In Swift, if you do not need to change the value to be processed, using constants can make our code more clearly express our intent and logic.
In addition to the familiar types, Swift also adds higher-order data types not available in Objective-C, such as Tuple ). Tuples allow you to create or pass a set of data. For example, when a function returns a value, we can use a single tuple to return multiple values.
Swift adds the optional (optional) Type to handle missing values. For the so-called optional types, it is clear if you have been in contact with OC. The optional type is like nil used in Objective-C, but it can be of any type, not just a class! Swift has an optional type which is safer and more expressive than the nil pointer in OC. It is an important part of Swift's many powerful types.
Constants and variables
Constants and variables must be declared before use. let is used to declare constants and var is used to declare variables.
For example:
1 let max = 10;2 3 var min =1;
Object (Objects)
Variables can also represent objects. The object type is the class name. Remember, class is the blueprint of this object. class contains all the attributes and behaviors of the object.
The following line of code usesvarIndicates that this is a variable.fastCarAs the variable name, the colon declares that this variable is of the object type. Here, it isCarFinally, the initial value of this variable is a new car object with equal signs:
var fastCar: Car = Car()
Variable in the string (Variables in Strings)
String interpolation can be used to directly add strings to variables. String insertion refers to the use of placeholders in a string to generate a string. After the program runs, these Placeholders are called directly. Here, strings are represented by double quotation marks, so Placeholders are represented\()The string to be inserted in the brackets. This method can be used to easily convert a non-string variable into a string type:
1 let seatsPerRow = 252 let numberOfRows = 253 var seatsString = "In the theater, there are \(numberOfRows) rows and \(seatsPerRow) seats in each row." //In the theater, there are 15 rows and 25 seats in each other row.
Type Inference)
Declaring a type for each variable and constant is a kind of physical activity. Apple engineers have been dedicated to making developer work easier. Based on the value on the right of the equal sign you provide, Swift can determine the type by itself, that is, it has the ability to deduce the type, which makes it easier to declare variables. See the following example:
1 var numberOfYears = 302 let name = "Steve"3 let isMale = true4 var bankAccountBalance = 1034.20
The type after the colon and colon is not needed, because Swift can infer the type based on the value on the right of the equal sign, and then automatically set the type of the variable. This saves a lot of time and simplifies the code.
Type annotation:
When declaring a constant or variable, we can add a type annotation to indicate the type of the value to be stored in the constant or variable. If you want to add a type annotation, you need to add a colon and space after the constant or variable name, and then add the type name.
For example:
1 var welcomeMessage: String
In welcomeMessage, we can understand it as: "declares a variable of the String type and its name is welcomeMessage"
String type indicates that any String type value can be stored.
WelcomeMessage = "Hello"
In Swift, you can use your favorite characters as constants and variable names, including Unicode characters!
For example, let $ = 3.3333, let Hello = "Hello word !", Let ?? = "Dogcow"
Note: constants and variable names cannot contain mathematical symbols, arrows, reserved (or invalid) Unicode code bits, connections, and tabs. It cannot start with a number, but it can contain numbers elsewhere in the constant and variable name.
NOTE: If we need to use the same keyword name in Swift as the constant or variable name, we can use reverse quotation marks (^) to enclose the keyword as the name, however, in any case, we should avoid using keywords as constants or variable names.
Collection)
In some cases, it is necessary to better organize many variables or constants together. Swift provides two Collection types to save and organize these variables.
Array (Arrays)
An Array is a container that stores multiple variables in a poly sequence. An array can store almost infinite elements (items), and each element has an array subscript that accurately specifies the position of this element in the array. You can declare an array as follows:
1 var names: [ String ] = [ "Steve", "Jeff", "Andy", "Andrew", "Cole", "Mike", "Mikey" ]
StartvarFollowed by a colon, followed by square brackets, which are arrays. On the right side of the equal sign, all array elements are enclosed by square brackets. Each array element is separated by commas.
In Swift, all elements in the array must be of the same type, which means that an array can store all strings, however, you cannot store two different types of elements, integer and string. Arrays can only store variables of the same type.
For an existing array, Swift can determine the type by itself, and there is no need to write the array type specifically, so the above array can also be written as follows:
1 var names = [ "Steve", "Jeff", "Andy" ]
You can also add an array to your array:
var names = [ "Steve", "Jeff", "Andy", "Wally" ] var parents = [ "Mike", "Adam", "Nick" ]names = names + parents // [ "Steve", "Jeff", "Andy", "Wally", "Mike", "Adam", "Nick" ]
Dictionary (Dictionaries)
An array is not a unique set type. A dictionary can store multiple variables and organize multiple variables together with keys and values. The working principle of the Key value is similar to that of the Oxford dictionary on your shelf. The Key is the word you want to search for, and the value is the meaning of the word. The dictionary is unordered, so you can only use the key to obtain a value. For example:
1 var homeruns : [ String : Int ] = [ "Posey" : 24, "Pagan" : 19, "Pence" : 15 ]
In this example, there are three keys ):"Posey","Pagan","Pence", Each key has a corresponding value. Increase the related keys and write them in brackets to get the corresponding values:
homeruns[ "Posey" ] // 24
Add a key value:
var homeruns : [ String : Int ] = [ "Posey" : 24, "Pagan" : 19, "Pence" : 15 ]homeruns[ "Sandoval" ] = 10 // [ "Posey" : 24, "Pagan" : 19, "Pence" : 15, "Sandoval" : 10 ]
Set the key value to null (nil) to delete the key value. Nil is a null value. We will give a more in-depth introduction to nil at the end of this chapter. Key-value deletion method:
1 homeruns [ "Sandoval" ] = nil // [ "Posey" : 36, "Pagan" : 19, "Pence" : 15 ]
Output constants and variables
In Swift, the print (_: separator: terminator :) function outputs the value of the current constant or variable:
Note: This is also the difference between the OC language
Swift uses string interpolation to add a constant or variable name to a long string as a placeholder. Swift replaces these placeholders with the values of the current constant or variable. Place the constant or variable name in parentheses and escape it with a backslash before the parentheses:
1 print ("The current value of friendlyWelcome is \ (friendlyWelcome)") // output "The current value of friendlyWelcome is Bonjour! 2 3
Use of semicolons
Unlike most other programming languages, Swift does not require the use of semicolons (;) at the end of each statement. You can also add semicolons as you like. In one case, the semicolon must be used, that is, we plan to write multiple independent statements in the same row:
Let cat = "? "; Print (cat) // output "? "
Type alias
Boolean Value
Swift has a basic Boolean Type called Bool. Boolean values are logical values because they can only be true or false. Swift has two Boolean constants: true and false:
let orangesAreOrange = truelet turnipsAreDelicious = false
When we compile conditional statements, such as if statements, Boolean values are very useful.
1 if turnipsAreDelicious {2 3 print ("Mmm, tasty turnips! ") 4 5} else {6 7 print (" Eww, turnips are horrible. ") 8 9} // output" Eww, turnips are horrible. "10 11
Tuples
Tuples combine multiple values into a composite value. The value in the meta-group can be of any type and is not of the same type.
let http404Error = (404, "Not Found")
We can combine any sequence of types into a single tuple, which can contain all types
1 let (statusCode, statusMessage) = http404Error2 3 print ("The status code is \ (statusCode )") // output "The status code is 404" 4 5 print ("The status message is \ (statusMessage)") // output "The status message is Not Found"