Swift Syntax 100

Source: Internet
Author: User
Tags case statement

1. Print Statements

2. Defining Constants and variables

Define a string constant with a variable let constantstring:string = "Hello"  //Let constant name: String type = "String" var variblestring:string = "World"   // var variable name: String type = "string"

3. Constants and variable types are automatically inferred, and types can be omitted when using declarations

Let Constantint:int = 1              //Common type has Int double Float stringvar pi = 3.14                         //compiler will automatically infer that pi is a double type

4. Type must match

5. The OUTPUT statement

Print (Constantint)                    //1print ("π value is: \ (pi)")                 

6. Type conversion

Let three = 3                         //Hold option, move the mouse over the variable name, click to view the constant type var pointonefour = 0.14               //system auto-infer the type of Pointonefour is: Doublepi = Double (three) + Pointonefour     //Only type can be manipulated, conversion format: type name (variable or constant) let piint = Int (pi)                   //double to int, the system automatically ignores the number after the decimal point, Will lose precision

7. Tuples

Tuples: Multiple sets of colors that can be of different types let Http404error = (404, "not Found")//Type: (Int, String), element types in tuples can be different lets (code, message) = Http404error    //Assign a tuple to a constant print ("Code:\ (Code), message:\ (Message)")//code:404, Message:not Foundlet (_, errormessage) = Http404error  //_ Can play the role of Ellipsis, which is widely applied in swift print (Http404error.1)                 //Not Found by subscript access element let ErrorCode = ( requesterror:401, 402, 403)//When defining tuples, you can name individual elements                

8. Optional type, if it is possible to assign a value of nil, it must be declared as an optional type

1. Optional type: The two state var errorcode:int used to represent a value or a value that is not valued? = 404              //Add one after type? print (ErrorCode)                       //Optional (404) ErrorCode = nil                        //assign nil to non-selectable type print (ErrorCode)                       //Nil

9. Use! Must not be nil in the inside

3. Using the IF statement to force resolution, the optional type cannot be directly used to convert if errorCode! = nil {                  //To determine the optional type contains the value can be added after the variable name! Force parsing  Print (errorcode!)                    404}

10. Optional binding, assigning an optional type to a temporary variable or constant

If let code = ErrorCode {    print (code)/                        /output: 404, Auto Parse}else {//    print (Code)                      //?, code is the local variable    print ( ErrorCode)                   //If ErrorCode = nil here outputs nil}

11. Implicit parsing of optional types: Because there must be value, so you can eliminate the trouble of parsing

" A "       // format: Optional type? change to! Print (assumedstring)                   //  Aif let tempstring = assumedstring {    //  Implicit parsing optional types can be used as normal optional types to use    print (tempstring)                  //  A}

12. Whether the string is empty

Emptystring2.isempty                   //True, the IsEmpty method is used to determine whether an empty

13. Traversing all characters of a string

The for char in emptystring1.characters {  //For loop will be followed by a verbose    print (char)                        //output all characters in EmptyString1}

14. Get the length of a string

EmptyString1.characters.count          //9, gets the number of characters in a string including spaces

15. Links to Strings

var string3 = string1 + string2        //Hello World, connect two strings by "+" String1.append ("!")                   Hello world!, stitching let messages = "Hello \ (string2) by append () Method!"    Hello World! By putting a constant or variable in \ ()

16. Interception of strings

Let Messchar = Messages[messages.startindex]  //H, gets the character by the index of the first character let FirstIndex = Messages.index (after: Messages.startindex)  //1, index of the first character let LastIndex = Messages.index (before:messages.endIndex)  //13, Index of last character let index = Messages.index (Messages.startindex, Offsetby:4)  //4, initial position offset 4messages[index]                        //O, The characters obtained by the index are OMESSAGES[MESSAGES.ENDINDEX]            //?, note: Indexes cannot be crossed

17. Creation of arrays

var arrtitle = [String] ()

18. Adding the array

Arrtitle.append ("Great value outing"), Arrtitle.append ("Select Tickets"), Arrtitle.append ("Enjoy the Tour");

19. Iterating the array

For Arritem in twodouble {//             traverse print    (arritem)                     ////print each element sequentially through a for In loop}

for (index, value) in twoDouble.enumerated() { // 使用迭代器获取数组元素以及索引号 print("索引:\(index), 元素:\(value)") // 依次打印索引号及元素 索引号:0, 元素:3.0 ...} 

20. Statement of the Dictionary

var chardict = ["Char1": "A", "char2": "B"]  //system will make automatic type inference, type can also be omitted

21. Adding a dictionary

chars["CHAR3"] = "C"  

21. Removal of the dictionary

22. Updating the dictionary

Chars.updatevalue ("B", Forkey: "Char2")    //Update key value pair, if this key does not exist, it will add a

23. The traversal of a dictionary

For (key, value) in Chardict {             //traverse all keys in dictionary value    print ("\ (key): \ (value)")              //char2:b newline char1:a}for key In Chardict.keys {                 //traverse all key in dictionary    print (key)                             //CHAR2 wrap char1}for value in Chardict.values {             //Traverse dictionary for all Value    Print (value)                           //B line break A}

Operation of 24.for Loops

For num in 1...5 {                     //To assign values in the closed interval [1, 5] to num    print (num)                         //Output 5 digits sequentially}

25.if/else

num = 3if num = = 3 {                          //If after Judgment statement returns to True, execute {} after {}    print (num)                         //If statement {} cannot omit}else {                                //If after Judgment statement returns FALSE, execute else after {}< C7/>print ("num is not equeal to 3")}

26.switch

num = 12switch num {case 2:    print ("num equals 2")                  //Each case branch must contain at least one statement    print ("num equals 2")                  //  The case branch end does not need to write a break and will not occur through the case 3, 4, 5:                         /////////////(,) to separate the    print ("num = = 3 or 4 or 5") between the multiple values, with (,). Case 6..<10:                          // The case statement also supports interval    print ("num is greater than or equal to 6 and less than ten") case 10..<19 where num% 3 = = 0:      //Use the Where statement to add additional judgment to    print (" Num is greater than or equal to 10 and less than 19 and divisible by 3 ") Default:    print (" None of the above ")}

27. Basic function: A separate code snippet to complete a specific task

Func Minmax (CurrentArray Array:[int]), (min:int,max:int) {                var currentmin = array[0];        var currentmax = array[0];        For Arritem in array {            if Arritem < currentmin            {                currentmin = Arritem;            }                        if (Arritem>currentmax)            {                Currentmax = Arritem;            }        }        Return (Currentmin,currentmax)    }

28. Functions that do not determine the number of parameters:

Computes the number of averages of the Func avaragenum (_ num:double ...), Double {///parameter appended ... Indicates that there are more than one parameter    var total:double = 0 for number in    num {total        + + #    }    return total/double (Num.coun T)}avaragenum (2, 6, 4, 8, 7)               //5.4, unlimited number of parameters Avaragenum (5)                           //Note: A function can have only one variable parameter

27. Network Request Framework

Alamofire.request ("Http://wimg.mangocity.com/bms/api/app/index/index.json", Method:. Get, Parameters:nil, encoding : Jsonencoding.default)            . DownloadProgress (Queue:DispatchQueue.global (QoS:. Utility)) {Progress in                print (" Progress: \ (progress.fractioncompleted)            }}            . Validate {Request, response, data in                debugprint (response)                return. Success            }            . Responsejson {response in                debugprint (response)        }

  

 

 

Swift Syntax 100

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.