Swift Learn (1)

Source: Internet
Author: User

Apple cancels the use of OC pointers and other unsafe accesses, the discarded Smalltalk syntax, which is completely changed to point syntax, provides a Java-like namespace paradigm overload;

First, let's look at the swift language. Swift, like the C language, uses variables to store and correlate values through variable names. Immutable variables are widely used in swift, which is what we often call constants. But Swift is far more powerful than the C-language constant. Remember that this is more powerful than C, not more powerful than C language. This should be understood clearly. In Swift, if you need to deal with values that do not need to be changed, the use of constants allows our code to express our intentions and logic more clearly.

In addition to our familiar types, Swift also increases the number of higher-order data types not found in objective-c such as tuples (tuple). Tuples allow you to create or pass a set of data, such as the return value of a function, we can use a tuple to return multiple values

Swift adds an optional (optional) type to handle the absence of a value. The so-called optional type, exposure to OC is certainly more clear. The optional type is like nil used in objective-c, but it can be on any type, not just class! Swift has an optional type of presence that is more secure 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, declare constants with Let, declare variables with VAR

For example:

1 Let max = 10;2 3 var min = 1;

Object (Objects)

A variable can also represent an object, and the type of the object is the name of the class. Remember, the class is the blueprint for this object, and the class contains all the properties and behaviors of the object.
The following line of code, with the var expression that this is a variable, used fastCar as the variable name, after the colon declares that the variable is the object type, here, is Car , finally, an equal sign indicates that the initial value of the variable is a new car object:

var fastcar:car = Car ()

Variables in the string (Variables in Strings)

With string interpolation, you can add a string directly to a variable. String insertion This term refers to the use of placeholders in a string to produce a string. These placeholders are called directly after the program is run. Here, the string is represented by double quotation marks, and the placeholder is represented by a \() string that needs to be inserted in two brackets. String insertion This method makes it easy to convert a non-string variable to a string type:

1 Let Seatsperrow = 252 let numberofrows = 253 var seatsstring = "In the theater, there is \ (numberofrows) rows and \ (sea Tsperrow) seats in each row. "   In the theater, there is all rows and seats in each other row.



Type extrapolation (type inference)

Declaring types for each variable and constant is a physical activity, and Apple's engineers have been working to make it easier for developers to work. Based on the value you provide to the right of the equals sign, Swift can determine its own type, which is the ability to have type inference, making it easier to declare variables. Please 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 to the right of the equals sign, and then automatically sets the type of the variable. This can save a lot of time and make the code more concise.

Type callout:

When we declare constants or variables, we can add type annotations, which describe the types of values to be stored in constants or variables. If you are adding a type callout, you need to add a colon and a space after the constant or variable name, and then add the type name.

For example:

1 var welcomemessage:string

In Welcomemessage we can understand that: "Declare a variable of type string, with Name Welcomemessage"

A type of string means that a value of any string type can be stored

Welcomemessage = "Hello"

We can use our favorite characters as constants and variable names in Swift, 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 illegal) Unicode code points, lines and tabs. You cannot start with a number, but you can include a number elsewhere in a constant and variable name.

Note: If we need to use the same name as constants or variable names with reserved keywords in swift, we can use the inverse quotation mark (^) to enclose the keyword in the same way as the name, but in any case we should avoid using the keyword as a constant or variable name.

collection (Collection)

In some cases, it is necessary to better organize a number of variables or constants, Swift provides 2 collection types to save and organize these variables.

Array (Arrays)

An array is a container in which multiple variables are stored in the order of the clusters. An array can store almost unlimited elements (item), and each element has an array subscript that accurately identifies the position of this element in the array. You can declare an array like this:

1 var names: [String] = ["Steve", "Jeff", "Andy", "Andrew", "Cole", "Mike", "Mikey")

The beginning or the next is the var colon, then the square brackets, the square brackets are the type of the array, the right side of the equal sign, surrounded by square brackets all the array elements, each element of the array is separated by commas.
In swift, all elements in an array must be of the same type, which means that an array can store all the strings, as in the example above, but cannot store integers and strings of 2 different types of elements. Arrays can only store variables of the same type.
For a given array, Swift can determine its own type and there is no need to specifically write out the type of the array, so the above array can also be written like this:

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)

Arrays are not unique collection types, dictionaries can also store multiple variables, and multiple variables are organized together with key (key) and values (value). The key value works like the Oxford Dictionary on your bookshelf, the key is the word you are looking for, and the value is the meaning of the word. Dictionaries are stored in an unordered order, so you can only use keys to get a value (value), for example:

1 var homeruns: [String:int] = ["Posey": "Pagan": +, "pence": 15]

In this example, there are three keys:,,, "Posey" "Pagan" "Pence" each key has a corresponding value. The corresponding value can be obtained by raising the associated key, which is written in brackets:

homeruns["Posey"]//24

Add a pair of key values:

var homeruns: [String:int] = ["Posey": "Pagan": +, "pence":]homeruns["Sandoval"] = ten    //["Posey" : "Pagan": +, "pence": "Sandoval": 10]

If you set the value of the key to null (nil), you can delete the pair of key values. Nil is a null value, we will introduce nil in more depth at the end of the chapter. To delete a key value method:

1 homeruns ["Sandoval"] = nil     //   ["Posey":, "Pagan": +, "pence": 15]

 

Output Constants and variables

Print (_:separator:terminator:) function in Swift to output the value of the current constant or variable:

Note: This is where the OC language is distinguished

Swift uses string interpolation (string interpolation) to add a constant name or variable name as a placeholder to a long string, and Swift replaces the placeholder with the value of the current constant or variable. Enclose the constant or variable name in parentheses and escape it with a backslash before opening the parentheses:

1 print ("The current value of Friendlywelcome is \ (friendlywelcome)")     //Output "The current value of Friendlywelcome is Bon Jour!2 3  

Use of semicolons

Unlike most other programming languages, Swift does not force us to use semicolons at the end of each statement (;), and you can, of course, add semicolons to your own custom. There is a case where a semicolon must be used, that is, we intend to write multiple separate statements in the same line:

123 letcat="?"print(cat//输出"?"

Type aliases

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:

123 letorangesAreOrange truelet turnipsAreDeliciousfalse

When we write conditional statements, such as the IF statement, the Boolean value is very useful

1 if turnipsaredelicious {2  3 print ("Mmm,tasty turnips!") 4  5} else {6  7 print ("Eww,turnips is horrible. ") 8  9}//output" Eww, turnips is horrible. " 10 11  

Meta-group

Tuples combine multiple values into a single composite value. The values within a tuple can be any type and do not require the same type

Let Http404error = (404,  "not Found")

We can combine any order type into a tuple that 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"

Swift Learn (1)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.