Basic swift type

Source: Internet
Author: User
1. Use let to declare constants and VaR to declare variables. Note: You can declare multiple constants or variables in a row and separate them with commas.

2. If the initial value does not provide enough information (or there is no initial value), you need to declare the type after the variable and separate it with a colon.
Let variable: String Note: Generally, you rarely need to write type annotations. If you assign an initial value when declaring a constant or variable, Swift can infer the type of the constant or variable.
3. Output Functions println and printprintln: they are global functions used for output. The output content is wrapped in a line break. Print: The only difference is that the output content does not end with a line break.
4. There is a simpler way to convert a value to a string: Write the value to the brackets and write a backslash before the brackets.
Let apples = 3 Let oranges = 5
Let applesummary = "I have \ (Apples) apples ."
Let fruitsummary = "I have \ (Apples + oranges) pieces of fruit ."

5. Single-line comment: // multi-line comment :/**/
6. Floating Point double: 64-bit floating point number. Use this type when you need to store large or high-precision floating point numbers. Float: 32-bit floating point number. This type can be used if the precision requirement is not high.
7. Type aliases is to define another name for an existing type. You can use the typealias keyword to define the type alias.
For example, a type alias is very useful when you want to give a more meaningful name to an existing type. Suppose you are processing data of external resources of a specific length: typealias audiosample = uint16
VaR minfound = audiosample. Min
VaR maxfound = audiosample. Max

8. Create a tuples (tuples) to combine multiple values into a composite value. The value in the meta-group can be of any type, but it is not required to be of the same type.
Example: Let http404error = (404, "not found ")
9. The content of the tuples can be decomposed into separate constants and variables. Let (statuscode, statusstr) = http404error
If you only need a portion of the values of the tuples, you can mark the ignored parts with underscores.
Let (justthestatuscode, _) = http404error

You can also use subscript to access a single element in the tuples. The subscript starts from scratch. VaR code = http404error. 0var MSG = http404error. 1
10. The optional value optionals forcibly parses an optional int to be written Int? Instead of int, it indicates that this integer variable may have a value, or it may be nil (no value ). 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.
Mandatory resolution of optional values: when you know that the optional values do contain values, you can add an exclamation point (!) after the optional names (!) To obtain the value.

11. Nil indicates no value. If you declare an optional constant or variable but do not assign a value, they are automatically set to nil:
VaR surveyanswer: string?

Note: Nil cannot be used for non-optional constants and variables. If your code contains constants or variables that need to handle Missing Values, declare them as optional types.

12. Implicit Parsing is optional. Sometimes, in the program architecture, after being assigned a value for the first time, you can determine that an optional item will always have a value. In this case, it is very inefficient to judge and parse the optional values every time, because it can be determined that there will always be a value.
In this case, we can use implicit parsing? Changed! You can.
13. Differences between implicit and optional values. Let possiblestring: string? = "An optional string ."
Println (possiblestring !) // Get the value with an exclamation point

Let assumedstring: string! = "An implicitly unwrapped optional string ."
Println (assumedstring) // No exclamation point is required
Note: If a variable may become nil, do not use implicit parsing. If you need to determine whether it is nil in the life cycle of the variable, use the normal optional type.

14. assertion can be used if some conditions are missing and we do not want the code to continue ). The assertion determines whether a logical condition is true. If it is true, the operation is executed; otherwise, the operation is aborted. Use the assert function to write assertions, such as: Let age =-3
Assert (age> = 0, "a person's age can not less than 0 ")
If age> = 0 is false, the assertion is triggered and the operation is aborted.
15. When to use assertion-the index of the appended script of the integer is passed into a custom appended script, but the index value of the subscript may be too small or too large.
-You need to input a value to the function, but the invalid value may cause the function to fail to run normally. -An optional value is now nil, but a non-nil value is required for subsequent code execution.
Note: assertions may cause your application to stop running, so you should carefully design your code so that invalid conditions do not appear. However, some illegal conditions may occur before your application is released. Using assertions can quickly discover problems.

16. Use square brackets [] to create arrays and dictionaries, and use subscript or key to access elements.
VaR shoppinglist = ["catfish", "water", "tulips", "blue paint"]

VaR occupations = ["Malcolm": "captain ",
"Kaylee": "mechanic",]

17. Create an empty array and dictionary. If the type information can be inferred, you can use [] and [:]. to create an empty array and an empty dictionary, just like when you declare a variable or pass a parameter to a function.


18. When a negative number is used to perform a remainder operation on a negative number-B, the-B symbol is ignored. This means that the result of a % B and A %-B is the same.
19. Closed range operator closed range operator A... B defines an interval that contains all values from A to B (including a and B.
20. semi-closed interval operator semi-closed interval .. <B defines a range from A to B, but does not include B. this is called a semi-closed interval because it contains the first value instead of the last value. Easy to use in arrays, such as: Let names = ["Anna", "Alex", "Brian", "Jack"] Let COUNT = names. count for I in 0 .. <count {println ("Th \ (I + 1) Name \ (Names [I])")}
21. The string literal code contains a predefined string value as a string literal. It can contain the following special characters: 1. escape special characters \ 0 (null), \ (backslash), \ t (horizontal tab), \ n (line break), \ r (carriage return), \ "(double quotation marks), \ '(single quotation marks ). 2. single-byte Unicode scalar, written as \ xnn, where NN is two hexadecimal numbers. 3. double-byte Unicode scalar, written as \ unnnn, where NNNN is a four-digit hexadecimal number. 4. Four-byte Unicode scalar, written as \ unnnnnnnn, where nnnnnnnn is an eight-bit hexadecimal number.
22. Identify var STR = "" str. isempty // true
23. The countelements function calls the global countelements function and passes the string as a parameter to obtain the number of characters in the string. VaR STR = "Andy is a good guy" countelements (STR)
24. Each entry of the string literal inserted by string interpolation is enclosed in parentheses prefixed with a backslash. Let multiplier = 3 Let message = "\ (multiplier) times 2.5 is \ (double (multiplier) * 2.5 )"
25. Comparison of strings swift provides three methods to compare string values: equal strings, equal prefixes, and equal suffixes. (1) equal strings: Use = to compare strings. (2) equal prefixes/suffixes: Call the hasprefix/hassuffix method of strings to check whether the strings have specific prefixes/suffixes, it returns a Boolean value.
26. You can use the uppercasestring and lowercasestring attributes of a string to access the uppercase/lowercase version of a string.
27. The SWIFT array should follow the format of array <sometype>. sometype is the only allowed data type in the array. We can also use simple syntaxes like sometype [] (recommended ).
If we create an array of the string value type, we cannot insert any data not of the string type into it. Arrays in swift are type-safe and must contain clear types. VaR shoppinglist: String [] = ["eggs", "milk"]
Because Swift has type inference, when we have array values of the same type, we can write them as VAR shoppinglist = ["eggs", "milk"]
28. Create an empty array to create an empty array of a specific data type. For example, create an empty array of the int type. VaR someints = int [] ()
29. array attributes and method (1) Count attributes: obtain the number of data in the array. (2) isempty attribute: Check whether the array has a value. (3) append/+ = method: You can use the append method or the + = Operator to add data items after the array. Example: shoppinglist. append ("Flour") or shoppinglist + = "baking powder" or shoppinglist + = ["Cheese", "butter"] (4) insert (atindex :) method: add a data item before a specific index value. For example, shoppinglist. insert ("maple syrup", atindex: 0) (5) removeatindex () method: remove an item from the array. This method removes the data items stored in the array in a specific index value and returns the removed data item. For example, let maplesyrup = shoppinglist. removeatindex (0) (6) removelast () method: remove the last entry from the array and return its value.

30. use subscript to change a series of data values even if the number of new data and original data is different. In the following example, replace "Chocolate spread", "Cheese", and "butter" with "Bananas" and "Apples": shoppinglist [4... 6] = ["Bananas", "Apples"]
31. array traversal generally involves a for-in loop. However, if we need the values and indexes of each data item, we need to use the global enumerate function to traverse the array. For example: for (index, value) in enumerate (shoppinglist ){...}
32. Create a specific size. The default data array // threedoubles is a double [] array, which is equal to [0.0, 0.0, 0.0] var threedoubles = double [] (count: 3, repeatedvalue: 0.0)
Because Swift has type inference, we do not need to specify the data type when using this constructor, because we know the data type from the value: vaR anotherthreedoubles = array (count: 3, repeatedvalue: 2.5)

33. dictionary is a storage that stores multiple types of data of the same type. Each value is associated with a unique key as the identifier of the value data in the dictionary. Note: keys and values that can be stored in a specific dictionary must be clearly defined in advance by explicit type annotation or type inference.
The swift dictionary is defined by dictionary <keytype, valuetype>. The keytype is the data type of the Middle-key in the dictionary, and the valuetype is the data type corresponding to the stored values of these keys in the dictionary. For example: var airports: dictionary <string, string> = ["tyo": "Tokyo", "Dub": "Dublin"]
Like arrays, if we use a literal statement to construct a dictionary, we do not need to define the type clearly. Airports can also be briefly defined using this method: var airports = ["tyo": "Tokyo", "Dub": "Dublin"]

34. The dictionary methods and attributes are basically the same as those of arrays. They all have similar methods and attributes, and they exist as follows: (1) updatevalue (forkey :) method: if this key does not have a corresponding value or an existing value is updated when it exists, this method returns the original value before the value is updated, so that we can check whether the update is successful. (2) removevalueforkey (keyname) method: If a key-Value Pair exists, the key-value pair is removed and the removed value or nil is returned if no value exists.
35. Remove a key-value pair. We can assign nil to the corresponding value of a key to remove the key-value pair. Airports ["APL"] = Nil
36. Use for-in for dictionary traversal: For (airportcode, airportname) in airports {...}
37. The dictionary's keys or values attributes represent a set of all keys or values in a dictionary. For airportcode in airports. Keys {...}
For airportname in airports. values {....}

38. Construct the key or value into a new array let airportcodes = array (airports. keys) // airportcodes is ["tyo", "lhr"] Let airportnames = array (airports. values) // airportnames is ["Tokyo", "London Heathrow"]

39. Create an empty dictionary var namesofintegers = dictionary <int, string> ()
NOTE: If an empty dictionary literal statement exists in the context, for example, namesofintegers [16] = "Sixteen", we can use namesofintegers = [:] to define an int, string-type empty dictionary.

Basic swift type

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.