Swift Rough Syntax

Source: Internet
Author: User

Document HTTPS://ITUNES.APPLE.COM/US/BOOK/THE-SWIFT-PROGRAMMING-LANGUAGE/ID881256329?MT=11 Http://download.csdn.net/de Tail/surfsky/7440835helloworld println ("Hello, World")----------------------------------------------------------  ---base-------------------------------------------------------------comment///**/semicolon line without a semicolon multiple statements on one line, plus a semicolon variable var MyVariable = 42 constant Let Myconstant = Explicitdouble:double =----------------------------------------------          ---------------data type-------------------------------------------------------------numeric type type Int:int32, Int64 Uint:uint32, Uint64 Double Float Various representations method let Decimalinteger = Binaryinteger = 0  b10001//In binary notation let Octalinteger = 0o21//+ octal notation let Hexadecimalinteger = 0x11// Hexadecimal notation Let decimaldouble = 12.1875 let exponentdouble = 1.21875e1 let Hexadecimaldoubl E = 0xc.3p0 Let PaddeddoubLe = 000123.456 Let onemillion = 1_000_000 bool (boolean) Let Orangesareorange = true let turnipsaredelicious = Fal Se vector Let (statusCode, statusmessage) = (404, ' not Found ') let (x, y) = (1, 2) Let Http200status = (statuscode:20 0, Description: "OK") println ("The Status code is \ (Http200status.statuscode)") string Let label = "the width is" le T width = 94 Let Widthlabel = Label + string (width) string added let apples = 3 let oranges = 5 Let AP        Plesummary = "I have \ (apples) apples." Let fruitsummary = "I had \ (apples + oranges) pieces of fruit." Array var shoppinglist = ["Catfish", "water", "tulips", "Blue paint"] shoppinglist[1] = "bottle of water" var Occupa tions = ["Malcolm": "Captain", "Kaylee": "Mechanic",] occupations["Jayne"] = "public Relations" let Emptyarray = Str Ing[] () shoppinglist = [] dictionary let emptydictionary = dictionary<string, float> () emptydictionary = [:] Null (NIL) and available is an empty object var serverresponsecode:int? = 404 Serverresponsecode = Nil----------------------------------------------let possiblestring:string?    = "An optional string."    println (possiblestring!) Let assumedstring:string!    = "An implicitly unwrapped optional string." println (assumedstring)------------------------------------------------------------- Data stream-------------------------------------------------------------if if i = = 1 {//This example'll compile SUCC essfully}switch Let vegetable = ' red pepper ' switch vegetable {case ' celery ': let Vegetab        Lecomment = "Add some raisins and make ants on a log."        Case ' cucumber ', ' watercress ': let vegetablecomment = ' would make a good tea sandwich. '        Case Let X where X.hassuffix ("Pepper"): let Vegetablecomment = "is it a spicy \ (x)?"    Default:let vegetablecomment = "Everything tastes good in soup." }for var firstforloop = 0 for var i = 0; I < 3; ++i {firstforloop + = 1} for I in 0..3 {firstforloop + = I}for (traversal array) Let Individualscores = [75 , 103, Teamscore = 0 for score in Individualscores {if score > {Teamscore + = 3} else {teamscore + = 1}} for (traversal dictionary) Let interestingnumbers = ["Prime": [2    , 3, 5, 7, one, all], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, +,],] var largest = 0                For (kind, numbers) in Interestingnumbers {for number in numbers {if number > largest {    largest = number}}}while var n = 2 while n < {n = n * 2}do...while var m = 2 does {m = m * 2} while M < 100 assertion (assert) let Age =-3 assert (age >= 0, "A per Son's age cannot is less than zero ")------------------------------------------------------------- function-------------------------------------------------------------function definition and call func greet (name:string, day:string), String {return ' Hello \ (name), today is \    (day). "}    Greet ("Bob", "Tuesday") returns multiple data func getgasprices (), (double, double, double) {return (3.59, 3.69, 3.79)            } getgasprices () unlimited number parameter func sumof (Numbers:int ...), Int {var sum = 0 for numbers in numbers { Sum + = number} return sum} sumof () Sumof (42, 597, 12) nested function func returnfifteen ()-I NT {var y = ten func Add () {y + = 5} add () Return y} returnfifteen ()  return function variable func makeincrementer ()--(int-int) {func AddOne (number:int), int {return 1 + Number} return AddOne} var increment = Makeincrementer () increment (7) function as input parameter (similar to lambda expression) Fu NC hasanymatches (list:int[], condition:int, BOOL), BOOL {for item in list {if condition (it   EM) {             Return True}} return False} func Lessthanten (number:int), Bool {        Return number < {var numbers = [7], hasanymatches (numbers, Lessthanten) closure Numbers.map ({ (Number:int), Int in Let result = 3 * number return result}) the name is substituted with the names sort ([1, 5, 3, 12, 2] ) {$ > $-------------------------------------------------------------}        Object and class-------------------------------------------------------------class definition class Shape {var numberofsides:int = 0 var name:string init (name:string) {self.name = name} func simpledescription ()-&G T        String {return "A shape with \ (numberofsides) sides."    }} using var shape = shape () shape.numberofsides = 7 var shapedescription = shape.simpledescription () self/super Self---this super---parent Inherits Class Square:namedshape {var sidelength:double iNIT (sidelength:double, name:string) {self.sidelength = Sidelength super.init (name:name)        Numberofsides = 4} func area (), Double {return sidelength * sidelength}        Override Func Simpledescription (), String {return "A square with sides of length \ (sidelength)." }} Let Test = Square (sidelength:5.2, Name: "My Test Square") Test.area () test.simpledescription () property Var p  erimeter:double {get {return 3.0 * Sidelength} set {sidelength = newvalue/3.0}} method overload override Func    Simpledescription (), String {return "an equilateral triagle with sides of length \ (sidelength)." }willset and Didset (property value set before and after processing) var Triangle:equilateraltriangle {willset {square.sidelength = Newvalu E.sidelength}} can call let Optionalsquare:square for an empty object method? = Square (sidelength:2.5, name: "Optional square") Let Sidelength = Optionalsquare?. SIdelength generics 
struct Pair<t:equatable> {let    a:t!    Let b:t!    Init (A:t, b:t) {        SELF.A = a        self.b = b    }    func equal () Bool {        return a = = b    }}let pair = Pa IR (a:5, b:10) PAIR.A//5PAIR.B//10pair.equal ()//false Let Floatpair = Pair (a:3.14159, b:2.0) FLOATPAIR.A//3.14159 FLOATPAIR.B//2.0floatpair.equal ()//False

-------------------------------------------------------------enumerations and struct-bodies------------------------------------------------------        -------enum enum Rank:int {case aces = 1 case, three, four, Five, Six, Seven, Eight, Nine, Ten Case Jack, Queen, King func-simpledescription (), String {switch self {case. Ace:return "Ace" case. Jack:return "Jack" case. Queen:return "Queen" case.                                          King:return "King" Default: Return String (Self.toraw ())}}} Let Aces = Rank.ace let Acerawva Lue = Ace.toraw () if Let Convertedrank = Rank.fromraw (3) {Let threedescription = Convertedrank.simpleDescription ()} looks a little dizzy. Enum Serverresponse {case Result (string, string) case Error (string)} Let        Success = Serverresponse.result ("6:00pm", "8:09 pm") Let failure = Serverresponse.error ("Out of cheese.") Switch success {case let.        Result (Sunrise, Sunset): Let Serverresponse = "Sunrise are at \ (Sunrise) and sunset are at \ (sunset)." Case Let. Error (Error):} struct struct Card {var rank:rank var suit:suit func simpledescription () S Tring {return "the \ (Rank.simpledescription ()) of \ (Suit.simpledescription ())"}} let Threeofspa Des = Card (rank:. Three, suit:. Spades) Let threeofspadesdescription = Threeofspades.simpledescription ()

Swift Rough Syntax

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.