1 //Playground-noun:a Place where people can play2 3 ImportCocoa4 5 //Control Flow6 7 //Swift's conditional statements include if and switch, loop statements contain for-in, for, and while and do-while, loop/judge conditions do not need parentheses, but loop/Judge body (body) required brackets:8Let individualscores = [75, 43, 103, 87, 12]9var Teamscore = 0Ten forscore in Individualscores { One ifScore > 50 { ATeamscore + = 3 -}Else{ -Teamscore + = 1 the } - } - - //Nullable Types + //with if and let, the nullable variable (nullable variable) can be handled conveniently. For null values, you need to add them after the type declaration? The display indicates that the type is nullable. -var optionalstring:string? = "Hello" +Optionalstring =Nil A atvar optionalname:string? = "John applesed" -var gretting = "Hello!" - ifLet name =optionalname{ -gretting = "Hello, \ (name)" - } - in //Flexible Switch -Let vegetable = "red pepper" to SwitchVegetable { + Case"Celery": -Let vegetablecomment = "Add som raisins and make ants on a log." the Case"Cucumber", "watercress": *Let vegetablecomment = "so would make a good tea sandwich." $ CaseLet X where X.hassuffix ("Pepper"):Panax NotoginsengLet vegetablecomment = "is it a spicy \ (x)?" - default: theLet vegetablecomment = "everything tastes good in soup." + } A the //Other Loops + //for-in can also be used to traverse a dictionary in addition to traversing an array -Let interestingnumbers = [ $"Prime": [2,3,5,7,11,13], $"Fibonacci": [1,1,2,3,5,8], -"Square": [1,4,9,16,25], - ] thevar largest = 0 - for(kind, numbers) in interestingnumbers{Wuyi forNumber in numbers{ the ifNumber >largest{ -largest = Number Wu } - } About } $ - //While loops and Do-while loops -var n = 2 - whileN < 100 { An = n * 2 + } the N - $var m = 2 the Do{ them = m * 2 the} whileM < 100 the m - in the //Swift supports traditional for loops, and also can be combined by: (Generate an interval) and for-in implement the same logic thevar firstforloop = 0 About forI in 0..3{ theFirstforloop + =I the } the Firstforloop + -var secondforloop = 0 the forvar i = 0; I < 3; ++i{BayiSecondforloop + = 1 the } the Secondforloop - //Note: Swift except for. And also... Among them. Create a front-closing interval, while ... Generates a closed-back interval. -var third = 0 the forI in 0...3 { theThird + =I the } theThird
Swift basic syntax (control flow, optional type, switch, loop, open space)