Swift Learning Note Four

Source: Internet
Author: User

Previous three notes some examples show some of Swift's features, a cursory introduction to its syntax and features, and a formal and systematic introduction to Swift's syntax and features, starting with this note.

Swift is a new language for iOS and OSX development, but it has a lot in common with C and objective-c.

Swift provides its own wrapper type for all C-language primitives and objective-c types, such as using int to identify integers, using double and float to identify floating-point values, string to identify text data, Swift also offers its own version of two major collection types: Array and dictionary.

Like C, Swift uses variables to save and reference values by its unique name, and Swift also uses immutable values, known as constants, that are more powerful than constants in C. The use of constants runs through Swift, making the code more secure and more concise.

In addition to those familiar types, Swift also adds new types that are not previously present, such as tuples (tuple), which allow you to create and pass in groups of values, and you can use tuples to return many values as a composite value from a function.

Swift also introduces an optional type (optional type) to handle values that may not exist. It thought, "Here's a value, it's equal to X" or "There's no value here."

The optional type is similar to nil in OC, but it applies to any type, not just the class object. It is also more secure, and many of Swif's core features are implemented using it.

An optional type is an example of a type-safe language, and if you specify that a variable is of type string, you cannot assign a value of type int to swif.

Constants and variables

Constants and variables have been described earlier, and if you are writing Swift code, if you determine that the value of a variable will no longer change, you should declare it as a constant with let whenever possible. The names of constants and variables can be almost any character, such as

3.14159 " Hello World  " "Dogcow

Of course, the name will still have some constraints, such as no arrows, horizontal lines, mathematical symbols, spaces, and can not start with a number.

After declaring a variable or constant, you cannot declare it with the same name, or convert the constant to a variable, or vice versa.

If you want to declare a variable using the Swift language name, use the (') symbol to wrap the keyword, which of course is not recommended unless it is a last resort.

Type declaration

You can indicate the type name of a variable or constant to tell the compiler what the variable is. However, in real-world development, it is seldom necessary to declare a type, because the compiler can infer the data type of the variable or constant as long as it is assigned an initial value when declaring a variable or constant. If you do not provide an initial value, you need to indicate the variable type.

Semicolon

In Swift, there is no requirement to add a semicolon at the end of each sentence, of course, with a semicolon, but if there are multiple expressions in a row, a semicolon must be appended to each expression.

Integral type (integers)

Swift provides 8, 16, 32, and 64-bit signed and unsigned integers similar to the C language, such as the 8-bit unsigned integer is UInt8, and the range of integers can be obtained through attributes such as:

Let MinValue = uint8.min  //  minValue are equal to 0, and are of type UInt8let MaxValue = uint8.max
   
    // 
     MaxValue is equal to 255, and is of type UInt8
   

Typically, do not write this, Swift provides a generic integer type int, which adjusts the range according to the actual running platform. Similar to this is the uint, which adapts to the unsigned integer type of the platform.

Integer variables can be used in a variety of binary notation, the decimal is directly written, the binary needs to add 0b prefix, octal need to add 0o prefix, hexadecimal need to add 0x prefix

Floating point number

Floating-point numbers are used to store numbers with decimal points, the range of floating-point numbers is much larger than integer, and Swift provides two types of floating-point numbers:

Double represents a 64-bit floating-point number

Float stands for 32-bit floating-point numbers

Double can be accurate to 15 digits after the decimal point, float only 6 bits. Choose one of the uses according to the actual usage, if both are suitable, double is recommended.

Floating-point numbers can be expressed in decimal (no prefix) and hexadecimal (0x prefixes) and must have digits on both sides of the decimal point. Can also be expressed in exponential notation (decimal with E, Hex with P):

1.25e2 is equivalent to 1.25x100, or 125.0 decimal in the scientific expression, the cardinality is 10

0XFP2 equivalent to 15x4, or 60.0 hexadecimal in a scientific expression, the cardinality is 2

The literal form of a number can have many formats, preceded by an arbitrary number of indents or 0, or underlined, which does not affect the integer and floating point types.

Different numeric types have different storage ranges (such as Int8 storage-128 to 127,uint8 storage 0 to 255), assigning values outside the range to the variable compiler will error, numeric types will not be implicitly automatically converted, you must display the type (through the initializer) to convert them:

Let twothousand:uint16 =1= Twothousand + UInt16 (one)//here itself UInt16 and UInt8 are not added

Type conversions between integral and floating-point types must also be shown to indicate, from integer to floating point and from floating-point to integral type.

Type aliases

Define a new name for the type that already exists by using the Typealias keyword.

Typealias audiosample = UInt16

You can use it anywhere you like with the original type name by defining an alias.

Booleans

Swift has a base Boolean type, called BOOL, and provides two Boolean constants of true and false.

Swift's type-safety mechanism prevents non-Boolean values from being implicitly converted to a Boolean type, such as:

1 if I {//change to If I==1 can     // This example would not compile, andwould report an error}

Meta-group

Tuples combine multiple values into a single composite value, and these values do not need to be of a uniform type. For example (404, "not Found") can be.

Tuples can also be decomposed into arbitrary constants or variables, which can be accessed as usual:

Let Http404error = (404"not Found"= http404errorprintln (" The status code is \ (statusCode)')//  prints "The status code is 404" 
    println ("Thestatus message is \ (statusmessage)")// prints "The status message is not Found

If you want only a subset of the tuple's value, the other parts can be ignored, then you can use underscores when decomposing tuples:

Let (Justthestatuscode, _) = http404errorprintln ("Thestatus code is \ (Justthestatuscode) " )//  prints "The status code is 404

Also, you can access the tuple's member values by using a numeric sequence number:

println ("Thestatus code is \ (http404error.0)")//  prints "the status Code is 404 "println (" Thestatus message is \ (Http404error.1)")// prints "The status message is not Found

When you define a tuple, you can also specify a name for each element, and then you can access the elements by name:

 $ " OK " ) println ("Thestatus code is \ (http200status.statuscode)")// prints "The status codeis a" println ("Thestatus message is \ (http200status.description) 
    ")//  prints" The status message is OK

Tuples are useful when organizing data temporarily, rather than creating complex, high-level data structures each time. But if the data needs to be organized in a long or complex way, it is more appropriate to use a class or structure.

Available options (optionals)

There is no option in C and OC, and the closest thing to it is that the function in OC can return an object or nil,nil means that the object does not exist. However, nil applies only to objects, C-language basic types, and other OC types. For other types, OC typically returns special values when needed (such as nsnotfound), which means that the function must know the type that should be returned, and Swift does not have this requirement, and the options are available for any type.

For a chestnut: the string type in Swift has a ToInt method to convert a string to int, but not all strings can be converted to int:

" 123 "  = possiblenumber.toint ()//  Convertednumber is inferred to be of type "Int?", or "optional I NT "

Nil

Setting the value of optionals to nil means that the value does not exist.

Note: Nil cannot be used to assign a value to a non-optional option. If a constant or variable may not have a value in some cases, set it as optional. Optional values are automatically set to nil if they are not assigned an initial value at the time of declaration

Swift's nil is not the same as nil in OC, where Nil in OC represents a pointer to a nonexistent object, and Swift's nil is not a pointer, it simply means that a value of a type does not exist.

You can determine whether an optional value exists by equal to nil. For example: if convertednumber! = nil So.

If you determine that a optionals value must have a value, you can access its actual value by adding an exclamation point after the Optionals value name, which is the forced expansion of the Optionals value:

if convertednumber! = Nil {    println ("convertednumber have aninteger value of \ ( convertednumber!). " )}//  prints "Convertednumber have an integer value of 123."

Note: A run-time error is triggered if the optionals value does not exist and the value is accessed by forcing the expansion.

Optional binding (Optional binding)

An optional binding is used to determine whether an optional option has a value, and if so, assigns it to a temporary constant or variable, typically through if and while:

if let Constantname = someoptional {    statements}

If Let Actualnumber = Possiblenumber.toint () {//This not only determines if it can be toint, but if it succeeds, it is already assigned to the constant Actualnumber
println ("\ ' \ (possiblenumber) \ ' Have an integer value of \ (Actualnumber)")
} else {
println ("\ ' \ (possiblenumber) \ ' could not is converted to an integer")
}

An optional binding can be either a constant or a variable, and you can have more than one optional binding in an if expression.

Implicit expansion options (implicitly unwrapped optionals)

As mentioned earlier, optionals means that a constant or variable allows "no value" and can be judged by the IF statement if it contains a value and then conditionally unfolded. Sometimes, through the structure of the code, you can determine that Optionals has a value after it has been owned. At this point, it is not necessary to determine the value of each time it has a value and the conditional expansion, this optionals is called the implicit expansion optional, when writing, in the case of the type with an exclamation point (such as: string!) Instead of a question mark (for example, String?).

An implicitly expanded optionals is useful when it is first defined, and then it can be determined that it will always have a value. Its main role in Swift is in the initialization of the class, which is described later.

The implicitly expanded optionals is still essentially a optionals, but can be used like a non-option value (nonoptional value) without having to expand each time the value is fetched. The following example shows the difference between an optional string and an implicitly expanded optional string when getting a value:

" An optional string. "  //  need exclamation point let assumedstring:string'animplicitly unwrapped optional String. "  //  No exclamation point required

It can be assumed that an implicitly expanded optionals is a optionals that is allowed to expand automatically when used. Instead of adding an exclamation mark at the back of each use, add an exclamation mark after the type name when declaring it.

If you access an implicit unwind optional that does not have a value, a run-time error is triggered, just as you would access a normal optional without a value.

Do not use implicitly unwrapped optionals when you are unsure whether its value will change to nil, and generally use optional directly.

Assertion

Optional is used to check if a value really exists in order to handle it, sometimes, when a value does not exist, there is no way to continue the program, you can use the assertion to interrupt the program, so you can debug.

An assertion is a run-time check that asserts that a condition is set first, runs normally if the run-time condition is met, and if the condition is not met, the program is interrupted and the application is terminated. If you are debugging the mode, you can precisely know the state of the program and the location of the interrupt.

To write an assertion through a global function assert:

Let age =-30"A person's age cannot is lessthan zero")// This description statement can be omitted at the back // This causes the assertion to trigger, because an age was not >= 0

Assertions cause the application to be terminated, it is not possible to avoid the wrong way, it is where the error is most likely to occur, before the formal release of the development phase to ensure that these errors will be discovered and clearly locked.

Swift Learning Note Four

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.