Swift Learning notes-1

Source: Internet
Author: User

Apple Official Development Brochure address:

Https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html


Syntax overview

1 Simple Values

Constant definition: let

Variable definition: var

Constant or variable type is consistent with the initial value:   var myvariable =   myvariable =   Myconstant = 42 can also be explicitly specified type: let  explicitdouble:d ouble = 70


Type conversion, for example, String ():

   Let label = ' the width is ' let   width = 94 let   Widthlabel = label + String (width)

Print constant/variable values using \()

    Let apples = 3 let    oranges = 5 let    applesummary = "I has \ (apples) apples."    Let fruitsummary = "I had \ (apples + oranges) pieces of fruit."

Create an array or dictionary. Use []:

    var shoppinglist = ["Catfish", "water", "tulips", "Blue paint"]    shoppinglist[1] = "Bottle of water"    var occupation s = [    "Malcolm": "Captain",    "Kaylee": "Mechanic",    ]    occupations["Jayne"] = "Public Relations"
Initialize an empty array or dictionary:

    Let Emptyarray = string[] () let    emptydictionary = dictionary<string, float> ()

2 Control Flow

Conditional Inference If/switch

loop control for-in for while Do-while

    Let individualscores = [103, +,]    var teamscore = 0 for    score in Individualscores {    if score > 5 0 {    Teamscore + = 3    } else {    Teamscore + 1    }    }    Teamscore


Switch case

    Let vegetable = ' red pepper '    switch vegetable {case    ' celery ': let    vegetablecomment = ' 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-in

    Let interestingnumbers = [    "Prime": [2, 3, 5, 7, one, +],    "Fibonacci": [1, 1, 2, 3, 5, 8],    "Square": [1, 4, 9, [+],    ]    var largest = 0    for (kind, numbers) in Interestingnumbers {for number in    numbers {    if num ber > Largest {    largest = number    }}}    largest

While/do-while

var m = 2do {m = m * 2} while M < 100m

For

Traditional format: var secondforloop = 0for var i = 0; I < 3; ++i {Secondforloop + = 1}secondforloop

New format: var firstforloop = 0for I in 0..3 {firstforloop + = I}firstforloop

3 Functions and Closures

    Function name (parameter 1, parameter 2), return type    func greet (name:string, day:string), String {    return ' Hello \ (name), today is \ (day). "    }    Greet (" Bob "," Tuesday ")

Returns multiple parameters:

    Func getgasprices () (double, double, double) {    return (3.59, 3.69, 3.79)    }    getgasprices ()

Variable number of parameters:

    Func sumof (Numbers:int ...)-Int {    var sum = 0 for number in    numbers {    sum + = number    }    return sum    }    Sumof ()    sumof (42, 597, 12)
Function nesting:

    Func Returnfifteen (), Int {    var y = ten    func Add () {    y + = 5    }    Add ()    return y    }
   
    returnfifteen ()
   
Returns the return value of a nested function:

    Func makeincrementer () (int-int) {    func addone (number:int), int {    return 1 + number    }    re Turn AddOne    }    var increment = makeincrementer ()    increment (7) <pre name= "code" class= "OBJC" >    Class Namedshape {    var numberofsides:int = 0    var name:string    init (name:string) {    self.name = Name
   }    func simpledescription (), String {    return "A shape with \ (numberofsides) sides."    }    }

There is a function to use as a parameter:

    Func hasanymatches (list:int[], condition:int-bool), BOOL {for    item in list {    if condition (item) {
   return true    }    }    return False    }    func Lessthanten (number:int), Bool {    return number < Ten    }    var numbers = [7, a, +]    hasanymatches (numbers, Lessthanten)

Use of {} and $

Numbers.map ({number in 3 * number})

Sort ([1, 5, 3, 2]) {$ > $}

4 Objects and Classes

Class implementation. Construct and destructor Init/deinit

    Class Namedshape {    var numberofsides:int = 0    var name:string    init (name:string) {       self.name = name       }    <code class= "Code-voice" >deinit</code> () {}     func simpledescription ()-String {          return "A shape with \ (numberofsides) sides."       }    }
Class uses:

    var shape = shape ()    shape.numberofsides = 7    var shapedescription = shape.simpledescription ()

Class inheritance and function overloading:

<pre name= "code" class= "OBJC" >class equilateraltriangle:namedshape {   var sidelength:double = 0.0   Initialize in subclass need to run:   1) Set subclass property Value   2) Parent class initialization   3) Set parent class Property value   init (sidelength:double, name:string) {     Self.sidelength = Sidelength     super.init (name:name)     numberofsides = 3  } var perimeter:double {  get {
   return 3.0 * Sidelength  }  set {    sidelength = newvalue/3.0  }}override func simpledescription ()- > String {    return ' an equilateral triagle with sides of length \ (sidelength). '  }}

Pre-set Willset and Didset
Willset {square.sidelength = newvalue.sidelength}

When working with optional values, you can write ?Before operations like methods, properties, and subscripting. If the value before the ?Is nil, everything after the ?

is ignored and the value of the whole expression is nil . Otherwise, the optional value is unwrapped, and everything after the?

Acts on the unwrapped value. In both cases, the value of the whole expression was an optional value.

    Let Optionalsquare:square? = Square (sidelength:2.5, name: "Optional square") let    sidelength = Optionalsquare?. Sidelength

5 enumerations and structures

Definition and use of 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    ace = Rank.ace let    acerawvalue = Ace.toraw ()
Conversion of enum values and raw values (Toraw and Fromraw)

    If Let Convertedrank = Rank.fromraw (3) {let    threedescription = Convertedrank.simpledescription ()    }

struct and class differences:

A struct is a copy when it is used. Class is quoted when it is used.


6 Protocols and Extensions

Declare a protocol

  Protocol Exampleprotocol {    var simpledescription:string {get}    mutating func adjust ()    }

Protocol use:

   Class Simpleclass:exampleprotocol {    var simpledescription:string = "A very simple class."    var anotherproperty:int = 69105    func adjust () {    simpledescription + = "Now 100% adjusted."    }    }    var a = Simpleclass ()    a.adjust () let    adescription = a.simpledescription    struct simplestructure: Exampleprotocol {    var simpledescription:string = "A simple structure"    mutating func adjust () {    Simpledescription + = "(adjusted)"    }    }    var b = simplestructure ()    b.adjust () let    bdescription = B.simpledescription

Notice the use of the keyword in the declaration's to mutating SimpleStructure mark a method, that modifies the structure.


Use of extension add functionality to an existing type

    Extension Int:exampleprotocol {    var simpledescription:string {    return "the number \ (self)    }    mutating Func adjust () {self    + =    -    simpledescription}}   


7 generics

Types of parameters to be determined:

    Func repeat<itemtype> (Item:itemtype, Times:int), itemtype[] {    var result = itemtype[] () for    i in 0. . times {    result + = Item    }    return result    }    repeat ("knock", 4)
Use whereTable with the list of references:

    Func anycommonelements <t, U where t:sequence, U:sequence, t.generatortype.element:equatable, T.GeneratorType.Eleme NT = = u.generatortype.element> (Lhs:t, rhs:u), Bool {for    Lhsitem in LHS {to    Rhsitem in RHS {    if L Hsitem = = Rhsitem {    return True    }}    }    return False    }    anycommonelements ([1, 2, 3], [3])


Swift Learning notes-1

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.