"Swift" Learning Notes (i)--familiar with basic data types, coding styles, tuples, advocates

Source: Internet
Author: User



Since Apple announced Swift, I have always wanted to know that he has not been able to take it to the formal learning, starting today, I will use my blog to drive Swift to know, as we know it is fast.






1. Defining variables and constants



var defines a variable , let defines a constant.






Like what:


var test = 1
test = 2 // variable can change value

let test = 1
test = 2 // The constant cannot change the value, the compiler will report an error

var test1 = 1, test2 = 2, test3 = 3 // Comma separated multiple variables








2. Add Type Callout



In the example of var test = 1. Test is judged by Swift as an int type.



Swift is type-safe.



var test:int = 1 The definition is the same as above. Just add a type callout to the test variable. Tell Swfit not to judge.






3. Basic data type



Int represents an integer value;Double and float represent floating-point values;bool is a Boolean value;String is text-type data;Character is a character type. Swift also provides two main collection types. Array and Dictionary















4. Global output function println and print



This is what everyone knows, the difference between line breaks and non-linefeed. Output to the console.






For example: println ("This is my first swift test")



What do I do now to output the test defined above?



println ("Test value = \ (Test)")



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, which is \ ()






5, gaze // when line gaze/ * /Fragment Gaze



6, the semicolon can not be. Arbitrary, but assume that a single line to write multiple independent statements will require a semicolon



For example: let test = "test"; println (Test)






7, integer integers are divided into signed (positive, negative, 0) and unsigned (positive, 0)



Swift offers 8, 16. 32 and 64-bit signed and unsigned integer types. These integer types and C languages are named very much like. For example, a 8-bit unsigned integer type is UInt8. The 32-bit signed integer type is Int32.



Just like the other types of Swift. An uppercase designation is used for integer types.


let minValue = UInt8.min // minValue is 0. Is the minimum value of type UInt8
let maxValue = UInt8.max // maxValue is 255. Is the maximum value of type UInt8


Int and UInt



Generally speaking. You do not need to specify the length of an integer specifically. Swift provides a special integer type int with the same length as the original word length of the current platform:



On 32-bit platforms, the int and Int32 lengths are the same.






On 64-bit platforms, the int and Int64 lengths are the same.









Swift also provides a special unsigned type uint that is the same length as the original word length of the current platform:

On a 32-bit platform. The UINT and UInt32 lengths are the same.
On 64-bit platforms, the uint and UInt64 lengths are equally



8. Floating point number



Double and Float



A floating-point number is a digit with a decimal part.

A floating-point type represents a larger range than an integer type. The ability to store numbers larger or smaller than the int type.



Swift provides two types of signed floating-point numbers:

A double represents a 64-bit floating-point number. Use this type when you need to store very large or very high-precision floating-point numbers.




Float represents a 32-bit floating-point number.



This type can be used if the accuracy requirement is not high.

Double accuracy is very high. There are at least 15 digits, and float has at least 6 digits. Which type to choose depends on the range of values that your code needs to handle.









9. Numeric literal






The entire number of digital polygons can be written:

A decimal number. No prefix
A binary number. Prefix is 0b
An octal number with a prefix of 0o
A hexadecimal number. Prefix is 0x



Floating-point literals can be either decimal (without a prefix) or hexadecimal (the prefix is 0x). There must be at least one decimal digit (or hexadecimal number) on either side of the decimal point. The floating-point literal is another optional exponent (exponent). specified in decimal floating-point numbers by uppercase or lowercase e. specified in hexadecimal floating-point numbers in uppercase or lowercase p.

Suppose that the exponent of a decimal number is exp. That number corresponds to the product of cardinality and 10^exp:

1.25e2 means 1.25x10^2, which equals 125.0.
1.25e-2 means 1.25x10^-2, which equals 0.0125.




Suppose that the exponent of a hexadecimal number is exp, which corresponds to the product of cardinality and 2^exp:

0XFP2 represents 15x2^2, equal to 60.0.
0xfp-2 represents 15x2^-2, equal to 3.75.
The following floating-point literals are equal to the decimal 12.1875:

Let decimaldouble = 12.1875
Let exponentdouble = 1.21875e1
Let hexadecimaldouble = 0xc.3p0
Numeric class literals can include additional formatting to enhance readability. Both integers and floating-point numbers can be added with an additional 0 and include underscores, without affecting the literal:

Let paddeddouble = 000123.456
Let onemillion = 1_000_000
Let justoveronemillion = 1_000_000.000_000_1





It looks like a headache, which is all the trouble with the decimal. The Spit groove is still a bit of a use.



。。






10. Type conversion of character types




var one: Int = 10
var two = 3.11
var three = Double (one) + two // Double has an integer constructor, and other integer types are treated the same, here is a demo example

11. Boolean Valuetrue False








12. Type alias Typealias



It doesn't make much sense to change a name to an integral type.



Poor reading. Like what




typealias MyInt = Int
var test: MyInt = 123





13, Tuples This is very important



Tuples (tuples) combine multiple values into a single composite value.



A value within a tuple can make a discretionary type. is not required to be the same type.



For example, create a tuple of type (int,string) : ("Server error")




let Mytuples = (500, "server error") // Define a tuple
let (code, message) = Mytuples // decompose tuple data into output
let (code, _) = Mytuples // Only the first value is required. Do not need to use _
println ("code is \ (code)") // output 500
println ("code is \ (Mytuples.0)") // Access by subscript Output 500
let Mytuples2 = (code: 500, message: "server error") // Define a tuple with parameter names
println ("code is \ (Mytuples2.code)"); // Access by tuple element name Output 500

14. Optional type





Use an optional type (optionals) to handle situations where the value may be missing.



The optional type represents:

has a value equal to X
Or
No value nil



Let Possiblenumber = "123"
Let Convertednumber = Possiblenumber.toint ()
Convertednumber was guessed as type "Int?"



", or type" optional Int "
Because the ToInt method may fail. So it returns an optional type (optional) int instead of an int. An optional int is written int?



instead of Int. The question mark implies that the included value is an optional type, which may include an int value or a value that may not be included.



(Cannot include other values, such as bool values or string values, regardless of value.) It can only be int or nothing. )




if convertedNumber {
    println("\(possibleNumber) has an integer value of \(convertedNumber!)")
} else {
    println("\(possibleNumber) could not be converted to an integer")
}
// prints "123 has an integer value of 123"
you can add an exclamation mark after an optional name (!) to get the value








It's a lot of trouble. It is also inferred that the variable has no value: use if inference, then use ! for forced parsing .



The ability to use optional bindings to simplify the code:




if let actualNumber = possibleNumber.toInt () {
     println ("\ (possibleNumber) has an integer value of \ (actualNumber)")
} else {
     println ("\ (possibleNumber) could not be converted to an integer")
}
// prints "123 has an integer value of 123"
can also be handled by implicitly parsing an optional type (determining that the variable will always have a value, otherwise it will go wrong)






let assumedString: String! = "An implicitly unwrapped optional string."
println (assumedString) // no need for an exclamation mark
// prints "An implicitly unwrapped optional string." 








15. Assertion inference logic true continue to run false end app



For example, let A = 1;assert (a >= 0) will trigger






Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.






"Swift" Learning Notes (i)--familiar with basic data types, coding styles, tuples, advocates


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.