1. Use let to declare constants and use VAR to declare variables.
Note: You can declare multiple constants or multiple variables in a row. separated by commas.
2. Type callout Assuming that the initial value does not provide enough information (or no initial value), you need to declare the type behind the variable and cut it with a colon.
Let variable:string Note: In general, you rarely need to write type callouts.
If you assign an initial value when declaring a constant or variable, Swift can determine the type of the constant or variable.
3, output functions println and PRINTPRINTLN: is a global function for output , the contents of the output are wrapped at the last line. Print: The only difference is that the output is not wrapped at the end of the line.
4, converting a value to a string has a simpler way to convert a value to a string: write the value in parentheses, and write a backslash before the parentheses.
let apples = 3 let oranges = 5
Let applesummary =" I has \ (apples) apples. "
Let fruitsummary = "I has \ (apples + oranges) pieces of fruit."
5, gaze-line gaze://Multiline gaze:/* */
6, floating-point number double: represents 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. The
7, type alias type alias (aliases) is a name for the existing type definition. You can use typealias keyword to define type aliases.
For example, type aliases are useful when you want to give a more meaningful name to an existing type. If you are working with data for a specific length of external resource: typealias audiosample = UInt16
var minfound = Audiosample.min
var maxfound = Audiosample.max
8, creating tuples tuples tuples (tuples) combines multiple values into a single composite value. Values within tuples can make arbitrary types and do not require the same type.
For example: let http404error = (404, "not Found")
9, The decomposition of a tuple's content enables a tuple to be decomposed into separate constants and variables for use.
Let (StatusCode, statusstr) = Http404error
Suppose you only need a subset of the tuple values, which can be marked with an underscore (_) when decomposing.
Let (Justthestatuscode, _) = Http404error
You can also access individual elements in a tuple by subscript, starting with zero. var code = http404error.0 var msg = Http404error.1
10, optional value optionals Force parsing an optional int is written int? Instead of int, it indicates that the shaping variable may have a value, or it may be nil (no value).
You can use an if statement to infer whether an optional value is included. Assuming the optional value, the result is true; assuming there is no value, the result is false.
Forced parsing of optional values: When you know that optional does include a value, you can add an exclamation mark (!) to the optional name. To get the value.
11, nil This means that there is no value. Assuming that you declare an optional constant or variable but have no assignment, they will voluntarily be set to nil:
var surveyanswer:string?
Note: nil cannot be used for non-optional constants and variables. If you have constants or variables in your code that need to deal with missing values, declare them as the appropriate optional type.
12, implicit parsing optional sometimes in the program schema, after the first assignment, you can determine that an optional always has a value. In such cases, it is inefficient to infer and parse an optional value every time, because it is possible to determine that it always has a value.
At this point we are able to use implicit parsing optional. Just need to put the back? Change it! We can.
13, implicitly selectable and optional value differences let possiblestring:string?
= "An optional string."
println (possiblestring!)//need an exclamation point to get the value
Let assumedstring:string! = "An implicitly unwrapped optional string."
println (assumedstring)//No exclamation point required
Note: Do not use implicit parsing if you assume that a variable may become nil. If you need to infer whether it is nil in the lifetime of the variable, use the normal optional type.
14, the assertion sometimes assumes that some conditions are missing. We can use assertions (assertion) If we don't want the code to continue running. The assertion infers whether a logical condition is true, assuming true to proceed. Otherwise, the execution is aborted. Use the Assert function to write assertions. For example: let Age=-3
ASSERT (age >= 0, "a person's age can not less than 0")
Because age >= 0 is false, the assertion is triggered and execution is aborted.
15, when to use the assertion-the satellite script index of an integer is passed into a self-defined satellite script implementation, but the subscript index value may be too small or too large.
-You need to pass a value to the function, but an illegal value may cause the function to not work properly.
-An optional value is now nil, but the subsequent code execution requires a non-nil value.
Note: Assertions can result in your app terminating execution, so you should design your code carefully so that illegal conditions do not appear. However, there are times when illegal conditions may occur before your app is published, and using assertions can detect problems at high speed.
16. Create arrays and dictionaries use square brackets [] to create arrays and dictionaries, and use subscripts or keys to access elements.
var shoppinglist = ["Catfish", "water", "tulips", "Blue paint"]
var occupations = [" Malcolm": "Captain",
"Kaylee": "Mechanic",]
17. Create empty array and dictionary assumptions type information can be judged, you can do enough[] and [:]To create an empty array and an empty dictionary-just as you would declare a variable or pass a reference to a function.
18, negative balance in the negative-B to seek redundancy,-B symbol will be ignored. This means that the result of a% B and a%-B is the same.
19, closed interval operator closed interval operator A...B defines an interval that includes all values from A to B, including A and B.
20, semi-closed interval operator semi-closed interval a. <b defines a range from a to B but does not contain B. This is called a semi-closed interval because the interval contains the first value and does not contain the last value. Easy to use in arrays, such as:Let names = ["Anna", "Alex", "Brian", "Jack"]Let count = Names.countFor I in 0..<count {println ("section \ (i + 1) personal name \ (Names[i])")}
21. The string literal code includes a pre-defined string value as a string literal, which can include the following special characters:1. Escape special characters (null character), \ \ (backslash), \ t (horizontal tab), \ n (line break), \ r (carriage return), \ "(double-cited), \ ' (single-cited). 2. Single-byte Unicode scalar. Written as \xnn, where nn is a two-digit hexadecimal number. 3. Double-byte Unicode scalar, written as \unnnn, where nnnn is a four-bit hexadecimal number. 4. Four-byte Unicode scalar, written as \unnnnnnnn, where nnnnnnnn is a eight-bit hexadecimal number.
22, String null attribute inferencevar str = ""Str.isempty//true
23. Countelements function by calling global countelements function. and passes the string as a parameter to get the number of characters in the string.var str = "Andy is a good guy"countelements (str)
24, string interpolation inserts a string literal for each item that is wrapped in parentheses prefixed by a backslash.Let multiplier = 3Let message = "\ (multiplier) times 2.5 is \ (Double (multiplier) * 2.5)"
25. The string is more than Swift provides three ways to compare string values: strings are equal, prefixes are equal and suffixes are equal. (1) String equality: that is, use = = to compare the string (2) prefix/suffix equal: By invoking the string'sHasprefix/hassuffixMethodTo check whether a string has a specific prefix/suffix. It returns a Boolean value.
26, string uppercase and lowercase you can access the uppercase/lowercase version number of a string by using the uppercasestring and LowerCaseString properties of the string.
27. Array type callout The Swift array should follow the form like array<sometype>. SomeType is the only data type in this array that is agreed to exist. We can also use simple syntax like sometype[] (recommended).
Suppose we create an array of string value types, and we cannot insert any data that is not a string type. Arrays in Swift are type-safe. And the types that they include must be understood.
var shoppinglist:string[] = ["Eggs", "Milk"]
Because Swift has type judgment. So when we have the same type of array values, we can write:var shoppinglist = ["Eggs", "Milk"]
28. Create an empty array to create an empty array of specific data types, such as creating an empty array of type int.
var someints = int[] ()
29. Properties and methods of the array (1) Count property: Gets the number of data in the array. (2) IsEmpty property: Checks if the array has a value. (3) Append/+ = method: We can use the Append method or the + = operator to add data items after the array. For example:shoppinglist.append ("flour") or shoppinglist + = "Baking Powder" or shoppinglist + = ["Cheese", "Butter"](4) in SERT (Atindex:) method: Adds a data item before a detailed index value. For example:shoppinglist.insert ("Maple syrup", atindex:0)(5) Removeatindex () method: Removes an item from the divisor group. This method removes the data items stored in the array at a particular index value and returns the removed data item.
Like what:Let Maplesyrup = Shoppinglist.removeatindex (0)(6) Removelast () method: Removes the last item in the array and returns its value.
30, the use of subscript to change a series of data values, even if the new data and the number of original data is not the same. The following example puts "chocolate Spread". "Cheese", and "Butter" are replaced by "Bananas" and "Apples":shoppinglist[4...6] = ["Bananas", "Apples"]
31, array traversal in general, for-in loops are possible, but assuming that we need the values and indexes of each data item, we need to use the global enumerate function for array traversal, such as:for (index, value) in enumerate (shoppinglist) { ...}
32, create a specific size, the default array of data//Threedoubles is a double[] array, equal to [0.0, 0.0, 0.0]var threedoubles = double[] (count:3, repeatedvalue:0.0)
since we have a type judgment on swift, there is no need to specify the data type when using such a construction method, since we know the type of the data from value:var anotherthreedoubles = Array (Count:3, repeatedvalue:2.5)
33. Dictionary dictionary is a kind of memory that stores the same type of multiple data. Each of the values (value) is associated with unique keys (key). Key as the identifier for this value data in the dictionary.Note: Keys and values that can be stored in a particular dictionary must be predefined and clearly defined. The method is judged by the explicit type annotation or type.
Swift's Dictionary usesDictionary<keytype, valuetype>Definition, where KeyType is the data type of the key in the dictionary. ValueType are the data types in the dictionary that correspond to the values stored by these keys. Like what:var airports:dictionary<string, string> = ["Tyo": "Tokyo", "DUB": "DuBlin "]
As with arrays, suppose we use literal statements to construct a dictionary without having to define the type clearly.
Airports can also be briefly defined in such a way:var airports = ["Tyo": "Tokyo", "DUB": "Dublin"]
34, the methods and properties of the dictionary, like the Basic and array, have similar methods and properties, and special existence such as the following: (1) updatevalue (Forkey:) method: Set the value when the key does not exist or update the existing value when it exists. This method returns the original value before the updated value. This makes it easy for us to check whether the update was successful.
(2) Removevalueforkey (KeyName) method: When a key value pair exists, it removes the key-value pair and returns the removed value or nil if there is no value.
35. Remove the key value pair we can assign nil to the corresponding value of a key to remove the key value pair.airports["APL"] = nil
36, the dictionary traversal using For-in can:for (Airportcode, Airportname) in airports { ...}
37. The Keys or values property of the dictionaryThese properties represent a collection of all keys or value for a dictionary. For Airportcode in Airports.keys { ... }
For Airportname in airports.values { .... }
38. Construct the key or value into a new arrayLet airportcodes = Array (Airports.keys)//Airportcodes is ["Tyo", "LHR"] Let airportnames = Array (airports.values)//Airportnames is ["Tokyo", "London Heathrow"]
39. Create an empty dictionaryvar namesofintegers = Dictionary<int, string> ()
Note: Assuming that the literal statement of an empty dictionary exists in the context, such as: namesofintegers[16] = "Sixteen", then we can use Namesofintegers = [:] To define an empty dictionary of type int, string.
Swift Foundation Type