Swift learning arrays, dictionaries, control flows

Source: Internet
Author: User

Playground-noun:a place where people can playimport uikit//2014-09-23 collection type Collection types//............. ....//1. Array/*1. \ \ \ \ \ \ \ \ \. Array is type-safe *///1.1 defines an array variable var shoppinglist:[string]=["Apple", "Eggs"]if shoppinglist.isempty {println ("the Shopping List is empty. ")} else {println ("The shopping list is not empty.")} Shoppinglist.append ("Orangle")//Array add element shoppinglist+=["1", "2"]//Array addition operator shoppinglist[0]= "six Apples"// Modifying an array element shoppinglist//1.2 can use subscripts to change a series of data values at once, even if the number of new and original data is different. But subscript cannot cross shoppinglist[2...4]=["A", "B"]//Put 2, 3, 43 elements into two elements, shoppinglist//1.3 insert element Shoppinglist.insert ("Z", Atindex:2) shoppinglist//1.4 remove element shoppinglist.removeatindex (0)//Remove the traversal of the first shoppinglist//1.5 array//1.51for item in    shoppinglist{Print (item+ "")}println ()//1.52 can use the global enumerate function for array traversal for (Index,value) in enumerate (shoppinglist) { println ("index is \ (index): value \ (value)")}//1.53 uses the construction syntax to create an empty array that consists of a specific data type var someint=[int] () someint+=[1,2,3] Someint=[]//into an empty shaped array//1.54 Swift in the array classType also provides a constructor that can create a specific size and that all data is default. var threedoubles=[double] (Count:3, repeatedvalue:0.0) var anotherthreedoubles = Array (Count:3, repeatedvalue:2.5) var s IXDOUBLES=THREEDOUBLES+ANOTHERTHREEDOUBLES//2. Dictionary/* in Swift, keys and values that can be stored in a particular dictionary must be defined in advance, by means of explicit type labeling or type inference. *///2.1var airports:dictionary<string,string>=["Tyo": "Tokyo", "DUB": "Dublin"]var charts=["a": "A", "B": "B"]// 2.2 Insert new value charts["C"]= "C" charts//2.3.1 modify charts["C"]= "CC" Charts/*2.3.2updatevalue (forkey:) function returns an optional value that contains a dictionary value type. For example, for a dictionary that stores string values, this function returns a string or a value of the "optional string" type. If the value exists, the optional value is equal to the value being replaced, otherwise it will be nil. */if let Oldvalue=charts.updatevalue ("CCCC", Forkey: "C") {println ("C ' s old value is: \ (oldValue)")}charts["D"]= "D" Char ts//2.3.3 uses subscript syntax to remove a key-value pair from the dictionary by assigning a value of nil to the corresponding value of a key charts[the "D"]=nilcharts/*2.3.4 Removevalueforkey method can also be used to remove key-value pairs in the dictionary. This method removes the key-value pair when the key-value pair exists and returns the removed value or returns the nil:*///2.4 dictionary traversal without a value println ()//2.4.1 uses the for-in loop to traverse the key values in a dictionary for the for (Charkey , charvalue) in charts{println ("\ (Charkey): \ (charvalue)")}//2.4.2 charts.values similar for charkey in charts.keys{println ("key,\ (Charkey)")}//2.4.3 get an array of key values let Chartkeyarray=array (charts.keys)/* Note: The dictionary type of Swift is an unordered collection type. where dictionary keys, values, key-value pairs are rearranged when traversing, and where the order is not fixed *///2.5 creates an empty dictionary var namesofintergers=dictionary<int,string> () namesofintergers[1]= "First" Namesofintergers//namesofintegers became an Int, an empty dictionary of type string namesofintergers=[:]// ...//3... ..... ..... ..... ...... ..... ..... ..... ..... ..... ..... ........... Control Flow//3.1 If you don't need to know the value of each item in the interval, you can use an underscore (_) to override the variable name to ignore access to the value: let base = 3let Power = 10var Answer = 1for _ in 1...power {answer    *= base println (answer)}println ("\ (base) \ (power) power is \ (answer)")//3.2 for condition self-increment for Var index=0;index<3;++index{ println (index)}//3.3 switch/* differs from the switch statement in C and Objective-c, in Swift, when the code in the matching case branch finishes executing, the program terminates the switch statement without continuing the next A case branch. This means that you do not need to explicitly use the break statement in the case branch. This makes the switch statement more secure, easier to use, and avoids errors caused by forgetting to write a break statement. */let somecharacter:character = "E" switch somecharacter {case "a", "E", "I", "O", "U": println ("\ (Somecharacter) is a Vowel ") case" B "," C "," D "," F "," G "," H ","J "," K "," L "," M "," N "," P "," Q "," R "," s "," T "," V "," w "," X "," Y "," Z ": println (" \ (somecharacter) is a consonant ") defa Ult:println ("\ (Somecharacter) is not a vowel or a consonant")}//output "E is a vowel"//3.3.2 interval matching let count = 3_000_000_00 0_000let countedthings = "stars in the Milky" Var naturalcount:stringswitch count {Case 0:naturalcount = ' no ' case 1...3:naturalcount = "A few" case 4...9:naturalcount = ' several ' case 10...99:naturalcount = ' tens of ' case 100: .999:naturalcount = "Hundreds of" case 1000...999_999:naturalcount = "thousands of" Default:naturalcount = "Mill Ions and millions of "}println (" there is \ (Naturalcount) \ (countedthings). ") Output "There is millions and millions of stars in the Milky." 3.3.3-Tuple matching/* You can use tuples to test multiple values in the same switch statement. An element in a tuple can be a value, or it can be an interval. Also, use an underscore (_) to match all possible values. */let somepoint = (1, 1) switch somepoint {case (0, 0): println ("(0, 0) was at the origin") case (_, 0): println (' (\ (so  mepoint.0), 0) is on the x-axis ') case (0, _):  println ("(0, \ (somepoint.1)) is on the y-axis") case ( -2...2, -2...2): println ("(\ (somepoint.0), \ (Somepoint.1)) are in Side the Box ") default:println (" (\ (somepoint.0), \ (Somepoint.1)) is outside of the box ")}//Output" (1, 1) is inside the Bo The pattern of the X "//3.3.4 value binding (value Bindings)/*case branching allows the matching values to be bound to a temporary constant or variable that can be referenced in the case branch-This behavior is called value binding. */let Anotherpoint = (2, 0) switch Anotherpoint {case (Let x, 0): println ("On the x-axis with a X value of \ (x)") Case ( 0, let Y): println ("On the y-axis with a Y value of \ (y)") (x, y): println ("somewhere else at (\ (x), \ (y))") }//output "on the x-axis with a X value of 2"//3.3.5 wherelet Yetanotherpoint = (1,-1) switch Yetanotherpoint {case let (x, Y) where x = = Y:println ("(\ (x), \ (y)) is on the line x = = y") case let (x, y) where x = =-y:println ("(\ (x), \ (y)) I s on the line x = = y ") case let (x, y): println (" (\ (x), \ (y)) are just some arbitrary point ")}//output" (1,-1) is on the L ine x = = y "//3.4 control transfer statement (controL Transfer statements)//switch through (Fallthrough)/*swift does not fall into the next case branch from the previous case branch. Instead, as soon as the first matching case branch completes the statement it needs to execute, the entire switch code block completes its execution. In contrast, the C language requires that you display the Insert break statement to the end of each switch branch to prevent automatic fall into the next case branch. The nature of Swift's avoidance of default falling into the next branch means that its switch function is clearer and more predictable than the C language, avoiding the errors that can be caused by unintentionally executing multiple case branches. If you do need a C-style through (Fallthrough) feature, you can use the Fallthrough keyword in each case branch that requires that feature. The following example uses Fallthrough to create a descriptive statement of a number. */let Integertodescribe = 5var Description = "the number \ (integertodescribe) is" switch Integertodescribe {case 2, 3, 5, 7 , one, all, 19:description, + = "A prime number, and also" fallthroughdefault:description + = "an Integer."} println (description)//Output "The number 5 is a prime number, and also an integer." 3.5 Tagged statements (labeled statements)/* Use tags to mark a loop body or switch block, and when using break or continue, take this tab and control the tag to represent the interrupt or execution of the object. */

Operation Result:






Swift learning arrays, dictionaries, control flows

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.