Swift Basic Notes

Source: Internet
Author: User
Tags case statement string format

Swift Case Sensitive

Swift Output Method println ()

Swift declares variable VAR declaration constants Let's note that let constants are only assigned when initialized, and VAR variables can be assigned at any time

The method for swift to output multiple variables in println is println ("\ (val1), \ (val2),...") which outputs the variable in double quotes (VAR)

Swift has several types of int Int8 Int16 Int32 Int64 bits for digital integral type. where int is automatically converted to the integer type of the current system bit based on the current operating system. For example, if the current system is 32 bits, then int is actually INT32

Swift gets the data type Range method: Take Int integer as an example, Int.max to get the maximum value of the type int.min to get the minimum value of the integer

If you want to improve the readability of your data in swift, you can write 1000000 as 1_000_000 so that writing does not affect the execution of the program, but also improves the readability of the code.

Swift SET data binary: binary 0b octal 0o hex 0x

The characters in the swift string: \ n (null character), \ \ (backslash), \ t (tab), \ nthe (new line character), \ r (carriage return), \ "(double quotation mark), \ ' (single quote)

Swift Single-byte Unicode character, with \xnn representation, where nn represents two hexadecimal digits

For example:

Let str = "\x41″

Output is "A"

Swift Double-byte Unicode characters, denoted with \unnnn, where nnnn represents 4 hexadecimal digits

For example:

Let str2 = "\u2600″

Output is *

Swift Four-byte Unicode character, denoted by \unnnnnnnn with nnnnnnnn representing 8 hexadecimal digits

For example:

Let STR3 = "\u0001f496″

Output to a special character

Swift String Case conversion:

Let small_string = "ABCD" Let big_string = "ABCD" println (small_string.uppercasestring) println (big_ string.lowercasestring)

As shown above,. uppercasestring is converted to uppercase. LowerCaseString is converted to lowercase

The For loop notation in Swift:

For key in value{println (key)}

Swift returns string length: Countelements(string)

Swift returns the Unicode character encoding for each character of the string:

For C in string.unicodescalars{print ("\ (C.value) \ n")}

How to: Swift Unary array types

Let name = (VALUE1,VLAUE2,VALUE3)

Where values can refer to other variables or constants

Let (var1,var2,var3) = name

You can assign values from a previously defined tuple to the 3 variables declared, and correspond in order one by one

Let (_,var2,_) =name

If you take only one or more of these values, the values you don't need need to be underlined instead

Let name = (VAR1:VALUE1,VAR2:VALUE2,VAR3:VALUE3)

You can name an element when you define a tuple, and you only need to name.var1 the call when you use it. Very similar to JavaScript

Nil in Swift indicates that the value does not exist by including another value or by including nil. By adding a question mark (?) after the type. To mark a value as an optional value. For example: Var value1:int?=nil sets an optional value. Of course, by default, adding a question mark after an expression will automatically set a nil value for the variable, for example: Var value2:int?

However, it is important to note that nil can only be assigned to the optional type (optional type). You cannot assign a value directly to a non-optional type, for example: var Value:int = nil This is wrong.

The value of the optional type, which needs to be converted after the variable is added! The contents of the optional values can be recalled separately. As shown in the following example:

var str = "123″var num:int?" = Str.toint () var num2 = num! + 100//Output 223

demo, the string str 123 is converted to int digital integer, converted to success, the actual content of the variable num is {some,123} at this time, if you print a picture with print, there will be no problem. But not directly for calculations, as in the example above: num2 if NUM does not! The error will be. So it can be understood here that the variable with the optional value is followed by the previous one! The valid values in the optional values can be raised and calculated.

Swift Custom Type:

Typealias id = uint8// custom type ID

var max = ID. Max// query type ID maximum range

var ID:id = ;// Set the type of the ID variable to ID and set the value to. If out of range will be an error

Swift Type conversions:

Use the. ToInt () mode when converting a character string to an integer int. The following example

var str_num:string = "123456″
var int_num:int? = Str_num.toint ()

Converts a character type variable str_num to an int type and assigns a value to Int_num. It is important to note that if you assign a type to a int_num, you must add the following type to the selected value. Because of the many uncertainties in the string, there are many cases when converting to an int type with characters. It is therefore necessary to set an optional value that displays nil when the converted string contains characters. In general, if you do not need to assign a variable to the type, you do not need to add?

Example: var int_num = Str_num.toint ()

Other types are converted to string type using the built-in method of ToString (). The following example

var int_num2 = 123456var str_num2 = ToString (int_num2)//Convert to string "123456″var str_num3 = toString (True)//Convert Boolean to String True

The data type conversion is simple to remember as a type (variable) to be converted. For example, to convert to Int16 type, then: Int16 (INT_NUM2)

If you want to convert to float type: float (int_num2)

Here are some of the characteristics of data conversion and calculation, as follows:

var str:int8 = 100var Str2:int16 = 200var str3:int16 = Int16 (str) + STR2

STR is the Int8 type and str2 is the Int16 type. If two numbers are added, you must first convert str to Int16 format and add it. Because Swift avoids the loss of precision, it is necessary to explicitly convert the Int8 type to the same type. Attention! It is not possible to convert STR2 to Int8 format for calculation.

Simple memory method for, can big turn small, cannot small turn big.

var intnum:int = 100var Floatnum = 1.911var tol = intnum + Int (floatnum)//Output 101

In the example above, it is an operation between an integral type and a floating-point type. Where intnum is of type int and floatnum is a double type. If two types are added to the drawing, one of the types must be converted to a different type of data for normal operation. Example converts a floatnum to an int type, and the result is 101 after the conversion and calculation. Description Floatnum After the type conversion, the data after the decimal point is discarded, so that the value of Floatnum becomes 1. The variable tol, if you do not specify any type of painting, is automatically converted to the normal computed type in the right-hand expression.

The Swift Hollow string is declared in the following way: var str = "" or var str = string () to determine whether the string is empty . IsEmpty when the property is used, the result is output in boolean form

The basic syntax for the swfit array is [Value1,value2,value3,.....]

The array declaration in swift can be specified as a type for arrays, or no type is specified for a group.

As an example:

var gril = ["Hanmeimei","teacher"]

The declared Gril array contains strings and numeric integers, because the array does not specify the appropriate content type, so it is legal to write this.

And the following example:

var gril:String[] = ["Hanmeimei",+, "Teacher"]

When an array is declared, a string type is specified for the contents of a set. If this is set, the program will error. Because 30 o'clock the integer class real number, if you must declare the type, be sure to convert the contents of the array to the same type.

Swift appends and deletes array elements in the following example:

var = ["Hanmeimei", "Gril", "Teacher"]gril.append ("China")//Use the Append method, which appends an element at the end of the array Gril.insert ("female", ATINDEX:1)//Use the Insert method when the method inserts a value at the specified position in the array. 0 is the starting position gril + = ["is Mother", "have one children"]//splicing the array with + =, the spliced content is appended to the end of the array gril.removeatindex (0)//using the Removeatindex method, Deletes a No. 0 array element. The return value of the method is the contents of the deleted array element, which can be assigned to a new variable to obtain the returned content, for example: var str = gril.removeatindex (0) At this time the value of STR is "Hanmeimei" gril.count// Count the number of elements in an array

There are two ways to iterate an array in Swfit:

1.for in for example:

For key in Gril{println (key)}

2. There is a loop variable traversal mode, you can get the subscript of the array, for example:

for (Index,value) in enumerate (gril) {println ("subscript = \ (index), value \ (value)}

This method first uses the enumerate method to process the Gril array element as a meta-array type, i.e. each traversal will be assigned (Index,value)

The basic syntax for the dictionary in Swift is: [Key1:val1,key2:val2,key3:val3,...]

As an example:

var city :Dictionary<string,string> = ["Key1″:" Wuhan "," Key2″: " Kunming "," Key3″: "Changsha"]

Create a city dictionary, which specifies a template for the dictionary in the previous example, where dictionary<string,string> represents the key for the specified dictionary as a string format, and Val is also a string format. When formatting a dictionary key and Val here, you need to be aware of the scope of the owning type.

City["Key4″] =" Guangzhuo "//Append Key4 value to dictionary guangzhou

Of course, modify the contents of the corresponding key value, you can also use this method, the value needs to assign a value to the specified key can be

Dictionaries can also use the. Count property to get the logarithm of a dictionary key value

For instructions on how to delete a dictionary by swift, use the following example to explain:

If Let RemoveValue = City.removevalueforkey ("Key2″") {println ("deleted key value is \ (removevalue)")//Print kunimng}else{println (" The corresponding \ "Key2\" key was not found)}

In the above example, the Removevalueforkey method is used. The method finds the Key2 key and deletes it, returning the value of its key. Where if expression, first determine whether Key2 exists. Returns true if Key2 exists, returns the deleted key value, and assigns the value to RemoveValue.

Swift's traversal of the dictionary is also available in two ways, as follows:

1.for in for example:

for (Index,value) in city{println ("Key \ (index), value \ (value)")}

2. Methods for traversing keys and values:

For Citykey in City.keys{println (Citykey)}

For CityName in City.values{println (CityName)}

As in the example above, traversing key can use the. Keys property, which can be used if you just traverse the values. Values Property

In fact, the. Keys and. Values two properties can also be converted to an array with the array () function to convert the keys or values that are taken, as follows:

Let Cityarray = Array (city. values)//Output [Changsha, Guangzhuo, Wuhan]

The SWIFT Branch statement contains the following two types:

The IF Else statement is consistent with other programs and is not described.

The switch statement, which differs greatly from other programs, has done a lot of optimizations, which are illustrated here using an example:

Let number = 12switchnumber{case 1,2,3,4,5,6,7,8,9,10:println ("1-10 digits") case11,12,13,14,15,16,17,18,19,20:println ( "Number between 10-20") default:println ("Number not within scheme range")} Let Number2 = 1_000switch number2{case 0:println ("0″) Case 1 ... 10:println ("1-10″) Case 11 ... 100:println ("11-100″) Case 101 ... 1000:println ("101-1000″) Case 1001 ... 10000:println ("1001-10000″") default:println ("Not in Scope")}

With the above two examples, you can find that the switch statement in Swift eliminates the break for each scheme (which can be understood as automatically adding break does not show), and the cut case scheme can be judged for any type of value. Case supports filtering of multiple values, such as Val1,val2,val3,... Or a range of values to filter, such as N1...n2

Swift's loop statement consists of four types:

1.while statements, same as other program statements, do not introduce

var i = 0while > I {println (i) i++}

2.do while statement

var n = 0do{println (n) n++}while100>n 3.for loop for Var i=0; i<100; i++ {println ("number \ (i)")} 4.for in loop is used primarily to traverse//1. Traverse range for index in 1 ... 5{PRINTLN (index)}//2. Ignores loop variables and is used only for calculation variables, but generally it is more appropriate to use a for or while to handle let base = 3let round = 20var Point = 1for _ in 1...round{p Oint *= base}println (point is \ (point))//3. Traversal array Let array = ["Val1", "Val2", "Val3"]for key in Array{println (key)}//4. Traverse dictionary var city:dictionary<string,string> = ["Key1": "Wuhan", "Key2": "Kunming", "Key3": "Changsha"]for (Index,value ) in City{println ("Key \ (index), value \ (value)")}//5. traversal string var str2 = "Swift" for key in Str2{println (key)}

Swift Jump Statement

1.continue statements

Continue instance, terminates the current loop, and executes the following loop

for var i = 0; i<100; i++ {if i%10 = = 0{continue;} println (i)}

2.break statements

Break instance, terminates the current loop, and ends the remaining loop

for var i = 0; i<100; i++ {if i = = 10{break;} println (i)}

3.fallthrough statements

You can let the schema selection in the switch statement continue to run through, similar to the effect of a case statement without a break after the case statements in other languages.

Let number2 = 1_000switch-number2{case 0:println ("0″) Case 1 ... 10:println ("1-10″) Case 11 ... 100:println ("11-100″) Case 101 ... 1000:println ("101-1000″) fallthrough//let the scheme match continue through case 1001 ... 10000:println ("1001-10000″") default:println ("Not in Scope")}

4.return statements

Generally used in the function of the return value used, and other programs basically similar, do not introduce

The SWIFT function is defined in the following example:

1. No value return function

Func Ourput (name:string,put:string) {println ("name \ (name), output \ (Put)"}

2. return function with value

Func ourput (name:string,put:string), String {println ("name \ (name), output \ (Put)") return Name+put}

The->string after the function parameter is the type that sets the return function, and if the type is specified it must have a return statement with a return statement, the type must be set for the return value

3. Multi-valued return function

Func Many (In1:string,in2:string,in3:int)-(set1:string,set2:string,set3:int) {var str1 = In1,str2 = In2,num = IN3STR1 + = str2 + String (num) return (str1,str2,num)}println (Many ("D1″," d2″,3))

4. Nesting functions

The nested function func gotheway (direction:bool)-(int)-int {////return value is actually a function pointer in a nested function, so also set the type for the parameter passed in by the nested functions, i.e. (INT) func Gofront ( Input:int), int {return input + 1}func GoBack (input:int), int {return Input–1}return Direction? Goback:gofront} var currentways = -4let Movetozero = gotheway (currentways > 0)//Because Gotheway is false, Movetozero in this case is actually a nested function In the Gofront. Note that the gotheways here can only pass in a Boolean type, because the function has only one parameter of the Boolean type. The Gotheways function returns the nested function to Movetozero only after the function has passed the corresponding parameter, and Gofront can work properly by Movetozero this function pointer whilecurrentways! = 0{println ( currentways) Currentways = Movetozero (currentways)}/************************************************************* ******/

First, constant & variable

Constant Let Constantsteam = 1//variable var variablesteam = 2

Use constants whenever possible, so that it is clearer and memory is less prone to kidney deficiency.

Second, show/implicitly specify type

Implicit let Inferredteam = 3//explicit Let Explicitteam:int = 4

Three, string output

Use \ (variable or constant name) to reference the combined string println ("\ (Inferredteam) is bigger than \ (Variablesteam)!")

Iv. Classes and methods

class uses the class keyword to declare class Tipcalculator {   //Create an attribute in a class let  total:double let taxpct:double let  subtotal: The Double   //property must be given an initial value at the time of declaration, or in initializer, otherwise it must be declared as optional (initializer is used here)  init (total:double, taxpct :D ouble) {    self.total = total    self.taxpct = taxpct    subtotal = total/(taxpct + 1)  }   //method using the Func keyword declaration , return double type  func calctipwithtippct (tippct:double), double {    return subtotal * tippct  }   // There is no return value method for  func printpossibletips () {    println ("15%: \ (calctipwithtippct (0.15))")    println ("18%: \ ( calctipwithtippct (0.18))    println ("20%: \ (calctipwithtippct (0.20))")  }}//Create class instance object, invoke method in class through class instance object let Tipcalc = Tipcalculator (total:33.25, taxpct:0.06) tipcalc.printpossibletips ()

V. Arrays and Loops

1let possibletipsinferred = [0.15, 0.18, 0.20]let possibletipsexplicit:[double] = [0.15, 0.18, 0.20]//2for possibletip i N possibletipsinferred {  println ("\ (possibletip*100)%: \ (calctipwithtippct (Possibletip))")}//3for I in 0..< Possibletipsinferred.count {let  possibletip = Possibletipsinferred[i]  println ("\ (possibletip*100)%: \ ( calctipwithtippct (Possibletip))}

VI. Dictionary Dictionary

1func returnpossibletips (), [int:double] {let   possibletipsinferred = [0.15, 0.18, 0.20] let  possibletips Explicit:[double] = [0.15, 0.18, 0.20]   //Create an empty dictionary  var retval = Dictionary<int, double> () for  Possibletip in possibletipsinferred {    let intpct = Int (possibletip*100)    //assignment to dictionary    retval[intpct] = calctipwithtippct (Possibletip)  }  return retval}



Swift Basic Notes

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.