Zhao yazhi _ Swift (1) _ introduction and type of swift, Zhao yazhi _ swift

Source: Internet
Author: User

Zhao yazhi _ Swift (1) _ introduction and type of swift, Zhao yazhi _ swift

Swift is a new language for iOS and OS X application development.

If you have C or Objective-C development experience, many content in Swift is familiar to you.

The Swift type is proposed based on C and Objective-C.

  • Int is an integer.
  • Double and Float are Float
  • Bool is Boolean
  • String is a String
  • Swift also has two useful collection types. For more information, see set types.
    • Array
    • Dictionary
  • Tuple ):
    • Swift also adds types not available in Objective-C.
    • Tuples allow you to create or pass a set of data. For example, when you return a value as a function, you can use a single tuple to return multiple values.
  • Optional (Optional) Type
    • When the processing value is missing.
    • (Optional) "there is a value and it is equal to x" or "there is no value ". Optional is a bit like using nil in Objective-C, but it can be used on any type, not just a class. The optional type is more secure and expressive than the nil pointer in Objective-C, and is an important part of Swift's many powerful features.

Just like the C language, Swift uses variables for storage and uses variable names to associate values.

Variable with immutable values is widely used in Swift. They are constants and are more powerful than constants in C. In Swift, if the value you want to process does not need to be changed, using constants can make your code safer and better express your intent.

 

Swift is a type-safe language. The optional language is a good example.

Swift allows you to clearly understand the value type. If your code expects a String, type security will prevent you from accidentally passing in an Int. You can detect and correct errors as early as possible during the development phase.


Data Type

Integer

An integer is a number without decimal digits, such as 42 and-23. Integers can be signed (positive, negative, zero) or unsigned (positive, zero ).

Swift provides 8, 16, 32, and 64-Bit Signed and unsigned integer types. These integer types are similar to those in the C language. For example, the 8-bit unsigned integer type is UInt8, and the 32-bit signed integer type is Int32. Like other types of Swift, the integer type adopts the upper-case naming method.

 Integer Range

You can access the min and max attributes of different integer types to obtain the maximum and minimum values of the corresponding types:

Let minValue = UInt8.min // The value of minValue is 0, which is the minimum value of UInt8 type. let maxValue = UInt8.max // The value of maxValue is 255, which is the maximum value of UInt8 type.

Int

Generally, you do not need to specify the length of an integer. Swift provides a special integer Int with the same length as the native character of the current platform:

  • On a 32-bit platform, Int and Int32 are of the same length.
  • On a 64-bit platform, Int and Int64 are of the same length.

Unless you need an integer of a specific length, Int Is generally enough. This improves code consistency and reusability. Even on 32-bit platforms, Int can store an integer range of-2147483648 ~ 2147483647, most of the time this is big enough.

 

UInt

Swift also provides a special unsigned UInt with the same length as the native character of the current platform:

  • On a 32-bit platform, Int and Int32 are of the same length.
  • On a 64-bit platform, Int and Int64 are of the same length.

Note: Do not use UInt unless you really need to store an unsigned integer with the same native character length as the current platform. In addition to this situation, it is best to use Int, even if the value you want to store is known to be non-negative. The unified use of Int can improve code reusability, avoid conversion between different types of numbers, and match the type speculation of numbers. Please refer to type security and type speculation.

 

Floating Point Number

A floating point number is a number with a decimal part, such as 3.14159, 0.1, and-273.15.

The floating point type has a larger range than the integer type. It can store numbers that are larger or smaller than the Int type. Swift provides two types of signed floating point numbers:

  • Double indicates a 64-bit floating point number. Use this type when you need to store large or high-precision floating point numbers.
  • Float indicates a 32-bit floating point number. This type can be used if the precision requirement is not high.

Note: The Double type is highly accurate and has at least 15 digits, while Float has at least 6 digits. The type you select depends on the range of values to be processed by your code.

 

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 = true let turnipsAreDelicious = false 

The orangesAreOrange and turnisaredelicious types are inferred to be Bool, because their initial values are Boolean literal values. Like Int and Double, If you assign true or false values to variables when creating them, you do not need to declare constants or variables as the Bool type.

When initializing a constant or variable, if the assigned value type is known, type speculation can be triggered, which makes Swift code more concise and readable.

 

When you write conditional statements such as if statements, Boolean values are very useful:

If turnipsAreDelicious {println ("Mmm, tasty turnips! ")} Else {println (" Eww, turnips are horrible. ")} // output" Eww, turnips are horrible ."

Conditional statements, such as if, refer to control flow.

 

If you use a non-Boolean value where the Bool type is required, the Swift type Security Mechanism reports an error. The following example reports a compilation error:

Let I = 1 if I {// This example will not pass compilation and an error will be reported}

However, the following example is valid:

Let I = 1 if I = 1 {// This example will be compiled successfully}

The comparison result of I = 1 is of the Bool type, so the second example can pass the type check. For comparison similar to I = 1, see Basic operators.

Like other types of security examples in Swift, this method can avoid errors and ensure that the intent of this Code is always clear.

 

Tuples

Tuples combines multiple values into a compound value. The value in the meta-group can be of any type, but it is not required to be of the same type.

In the following example, (404, "Not Found") is a tuple describing the HTTP status code. The HTTP status code is a special value returned by the web server when you request a webpage. If the requested webpage does Not exist, a 404 Not Found status code is returned.

<Span style = "color: #666666;"> let http404Error = (404, "Not Found") // The type of http404Error is (Int, String), and the value is (404, "Not Found") </span>

(404, "Not Found") tuples combine an Int value and a String value to indicate two parts of the HTTP status code: a number and a human-readable description. This tuples can be described as "a type of (Int, String) tuples ".

 

You can combine any sequence of types into a single tuple, which can contain all types. As long as you want, you can create a type of (Int, Int, Int), (String, Bool), or any other tuples that you want to combine.

 

You can break down the content of a tuples (decompose) into separate constants and variables, and then you can use them normally:

Let (statusCode, statusMessage) = http404Error println ("The status code is \ (statusCode )") // output "The status code is 404" println ("The status message is \ (statusMessage)") // output "The status message is Not Found"

If you only need a part of the values of the tuples, you can mark the ignored parts with underscores:

Let (justTheStatusCode, _) = http404Error println ("The status code is \ (justTheStatusCode)") // output "The status code is 404"

 

In addition, you can use subscript to access a single element in the tuples. The subscript starts from scratch:

Println ("The status code is \ (http404Error. 0) ") // output The status code is 404" println ("The status message is \ (http404Error. 1) ") // output" The status message is Not Found"

You can name a single element when defining the tuples:

let http200Status = (statusCode: 200, description: "OK")

After naming the elements in the tuples, you can obtain the values of these elements by name:

Println ("The status code is \ (http200Status. statusCode) ") // output The status code is 200" println ("The status message is \ (http200Status. description) ") // output" The status message is OK"

Tuples are useful when they are returned as function values. A function used to obtain a webpage may return a (Int, String) tuples to describe whether the webpage is obtained successfully. Compared with returning only one type of value, a tuples containing two different types of values can make the function return more useful information. See function parameters and return.

 

Note: tuples are useful for temporary organization values, but they are not suitable for creating complex data structures. If your data structure is not used temporarily, use a class or struct instead of a tuples. See classes and struct.

 

Optional

Use optional (optionals) to handle possible missing values. Optional values:

  • Value, equal to x
  • No value

Note: C and Objective-C do not have the optional concept. The closest thing is a feature in Objective-C. If a method does not return an object or nil, nil indicates "a valid object is missing ". However, this only works for objects-for struct, the basic C type or enumeration type does not work. For these types, the Objective-C method generally returns a special value (such as NSNotFound) to indicate that the value is missing. This method assumes that the caller of the method knows and remembers to judge the special value. However, the Swift option allows you to imply that any type of value is missing without a special value.

 

Let's look at an example. The Swift String type has a method called toInt, which is used to convert a String value into an Int value. However, not all strings can be converted into an integer. The string "123" can be converted to a number 123, but the string "hello, world" cannot.

 

The following example uses the toInt method to convert a String to an Int:

Let possibleNumber = "123" let convertedNumber = possibleNumber. toInt () // convertedNumber is assumed to be of the type "Int? ", Or type" optional Int"

Because the toInt method may fail, it returns an optional (optional) Int instead of an Int. An optional Int is written as an Int? Instead of Int. The question mark implies that the included value is optional, that is, it may contain an Int value or not. (It cannot contain any other value, such as a Bool value or a String value. It can only be Int or nothing .)

 

If statement and forced resolution

You can use the if statement to determine whether an optional value is included. If the value is optional, the result is true. If there is no value, the result is false.

After you confirm that the optional package does contain values, you can add an exclamation point (!) after the optional name (!) To obtain the value. This exclamation point indicates "I know this option has a value. Please use it ." This is called mandatory resolution of optional values (forced unwrapping ):

If convertedNumber {println ("\ (possibleNumber) has an integer value of \ (convertedNumber !) ")} Else {println (" \ (possibleNumber) cocould not be converted to an integer ")} // output" 123 has an integer value of 123"

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.