Apple Swift programming language Getting Started Tutorial

Source: Internet
Author: User
Tags constant definition

1 Introduction

Apple has just released the Swift programming language early this morning, extracted from its published book, the Swift programming Language. We hope to help you with your IOS&OSX development.

Swift is a new programming language for iOS and OS X applications, based on C and objective-c, without some of the compatibility constraints of C. Swift uses a secure programming model and adds modern features to make programming easier, more flexible, and more fun. The interface is based on the cocoa and cocoa touch framework, which is popular with the people, and shows the new direction of software development.

Swift has existed for many years. Apple is based on an existing compiler, debugger, and framework as its infrastructure. Simplify memory management with arc (Automatic Reference counting, auto reference count). Our framework stack is always based on cocoa. Objective-c Evolution supports blocks, collection literal, and modules, allowing the framework of modern languages to be used without deep access. Thanks to these basic work, the new programming language can be introduced in Apple software development (by Gashero).

OBJECTIVE-C developers will feel Swift's déjà vu. Swift uses objective-c named parameters and a dynamic object model. Provides interoperability with the cocoa framework and the mix-and-match. Based on these fundamentals, Swift introduces a number of new features and a combination of process-oriented and object-oriented features.

Swift is also friendly to the new programmer. He is an industrial-quality system programming language, yet as friendly as a scripting language. He supports playground, allowing programmers to experiment with a swift code feature and immediately see results without having to build and run an application in a hassle.

Swift integrates modern programming language ideas and the wisdom of Apple's engineering culture. Compilers are optimized for performance, and languages are optimized for development without compromising on each other. (by Gashero) can start from "Hello, World" to learn and transition to the entire system. All of this makes swift a source of innovation for Apple software developers.

Swift is a fantastic way to write iOS and OSX apps, and will continue to drive the introduction of new features. We can't wait to see you do something with him.

2 Getting Started with Swift

Learning a new language should start with the print "Hello, World". In Swift, there is one line:

println ("Hello, World")

If you have written C or objective-c code, this syntax looks familiar, and in Swift, this is the complete program. You do not need to import (import) a separate library for input and output and string processing. The globally scoped code is the entry for the program, so you don't need to write a main () function. You do not have to write semicolons after each statement.

This primer will give you enough information to teach you to complete a programming task. No need to worry that you do not understand some things, all the unexplained, will be explained in detail later in this book.

Note

As a best practice, you can open this chapter in the playground of Xcode. Playground allows you to edit the code and see the results immediately.

3 Simple values

Use let to define constants, var to define variables. The value of a constant does not need to be specified at compile time, but is assigned at least once. This means that you can use constants to name a value, and you find that you only need to be sure once, but in multiple places.

var myvariable = 42myVariable = 50let Myconstant = 42

Note

Gashero notes

The constant definition here is similar to a variable in a functional programming language and cannot be modified once it is assigned. A lot of use is good for health.

A constant or variable must have the same type as the assignment. So you don't have to strictly define the type. You can create a constant or variable by providing a value, and let the compiler infer its type. In the example above, compiling it would infer that myvariable is an integer type because its initialization value is an integer.

Note

Gashero notes

The type is bound to the variable name and belongs to the static type language. contributes to static optimization. It differs from Python, JavaScript, and so on.

If the initialization value does not provide enough information (or no initialization value), you can write the type after the variable name, separated by a colon.

Let Imlicitinteger = 70let imlicitdouble = 70.0let explicitdouble:double = 70

Note

Practice

Create a constant with a type of float and a value of 4.

Values are never implicitly converted to other types. If you need to convert a value to a different type, explicitly construct an instance of the desired type.

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

Note

Practice

What error would you get if you tried to remove the string conversion from the last line?

There is also an easier way to include values in a string: Write the value in parentheses, and precede the parentheses with a backslash (""). For example:

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

Note

Practice

Use () to include a floating-point number to calculate to a string, and to include someone's name to greet.

Create an array and a dictionary using square brackets "[]", accessing its elements by means of an index or key in square brackets.

var shoppinglist = ["Catfish", "water", "tulips", "Blue paint"]shoppinglist[1] = "bottle of water" var occupations = [   "Malcolm": "Captain",   "Kaylee": "Mechanic",]occupations["Jayne"] = "Public Relations"

To create an empty array or dictionary, use the initialization syntax:

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

If the type information cannot be inferred, you can write an empty array for "[]" and an empty Dictionary for "[:]", for example if you set a variable to know and pass in a parameter to the function:

Shoppinglist = []   //GO shopping and buy something by Gashero
4 Control Flow

Use if and switch as conditional controls. Use for-in , for, while, and do-while as loops. The parentheses are not required, but the main braces are required.

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

In an if statement, the condition must be a Boolean expression, which means that if score {...} is wrong and cannot be suppressed compared to 0.

You can use if and let together to prevent the loss of values. These values are optional. An optional value can contain a value or contain a nil to specify that the value does not already exist. Write a question mark "?" After the type indicates that the value is optional.

var optionalstring:string? = "Hello" optionalstring = = Nilvar optionalname:string? = "John appleseed" var greeting = "Hello!" If let name = optionalname {    greeting = "Hello, \ (name)"}

Note

Practice

Change Optionalname to nil. What happens when you greet? Add an Else clause to set a different value when Optionalname is nil.

If the optional value is nil, the condition is false the code in the curly braces is skipped. Otherwise, the optional value is not wrapped and assigned to a constant, which will be the non-wrapped value of the variable into the code block.

Switch supports multiple data and multiple comparisons, without limiting the need to be integers and test equality.

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:    //by gashero let    vegetablecomment = "Everything tastes good in soup."}

Note

Practice

Try to get rid of the default and see what's wrong.

After the match is performed, the program jumps out of the switch instead of continuing to the next situation. So you no longer need break to jump out of switch .

You can use for-in to iterate through each element in the dictionary, providing a pair of names to use each key-value pair.

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

Note

Practice

Add another variable to keep track of which kind of number is the largest, that is, where the largest number resides.

Use the while to repeat the code block until the condition changes. The condition of the loop can be placed at the end to ensure that the loop executes at least once.

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

You can keep an index in the loop that represents the index range or explicitly declares an initial value, condition, increment. The two loops do the same thing:

var firstforloop = 0for I in 0..3 {    Firstforloop + = I}firstforloopvar Secondforloop = 0for var i = 0; i < 3; ++i {    Secondforloop + = 1}secondforloop

Use : to construct a range that ignores the highest value while using the ... constructed range contains two values.

5 Functions and closures

Declare a function with func . The calling function uses his name plus the argument list in parentheses. The name and return value type of the delimited parameter is used.

Func greet (name:string, day:string), String {    return ' Hello \ (name), today is \ (day). "} Greet ("Bob", "Tuesday")

Note

Practice

Remove the day parameter and add a parameter containing today's lunch selection.

Use tuple (tuple) to return multiple values.

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

The function can accept a variable number of parameters and collect it into an array.

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

Note

Practice

Write a function to calculate the average of its parameters.

Functions can be nested. Inline functions can access the variables of the function whose definition is located. You can use inline functions to organize your code to avoid too long and too complex.

Func Returnfifteen (), Int {    var y = ten    func Add () {        y + = 5    }    Add ()    return y}   //by Gashero Returnfifteen ()

The function is the first type. This means that the function can return another function.

Func makeincrementer () (int-int) {    func addone (number:int), int {        return 1 + number    }    r Eturn Addone}var increment = Makeincrementer () increment (7)

A function can accept other functions as arguments.

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 < 10}var Numbe rs = [7, 12]hasanymatches (Numbers, Lessthanten)

The function is actually a special case of closures. You can write a closure without a name, just put it in curly braces. Use in to the return value of a specific parameter and body.

Numbers.map ({    (number:int)-Int in let    result = 3 * Number    return result    })

Note

Practice

Override a closed package to return 0 for all odd numbers.

There are several options for writing closures. When a closure type is known, such as a callback, you can ignore its arguments and return values, or both. A closure of a single statement can return a value directly.

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

You can refer to a parameter by a number instead of a name, which is useful for very short closures. A closure passes its last argument to the function as the return value.

Sort ([1, 5, 3, 2]) {$ > $}
6 Objects and classes

Use class to create a class. The declaration of a property is declared in a class as a constant or variable, except in the context of the class. Methods and functions are also written in this way.

Class Shape {    var numberofsides = 0    func simpledescription ()-String {        return ' A Shape with \ (numberofsid ES) sides. "    }}

Note

Practice

Add a constant property through "let", and add another method to accept the argument.

Create an instance of the class by enclosing the class name with parentheses. Use point syntax to access the properties and methods of an instance.

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

Something important in this version of the Shape class is not: A constructor to set the class when the instance is created. Use init to create a.

Class Namedshape {    var numberofsides:int = 0    var name:string    init (name:string) {        self.name = name    }   //by Gashero    func simpledescription (), String {        return "A Shape with \ (numberofsides) sides."    }}

Note Self is used to differentiate between the Name property and the name parameter. The constructor's life is the same as a function, except that an instance of the class is created. Each property needs to be assigned, both in the Declaration and in the constructor.

Use deinit to create a destructor to perform cleanup work when the object is destroyed.

Subclasses include the names of their superclass, separated by colons. There is no need to declare when inheriting the standard root class, so you can ignore the superclass.

A method of a subclass can overload an implementation in a superclass by marking Override , and no override is considered an error by the compiler. The compiler also checks for methods that are not overloaded.

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 \ (SideL ength). "    }} Let test = Square (sidelength:5.2, Name: "My Test Square") Test.area () test.simpledescription ()

Note

Practice

The subclass of writing another namedshape is called Circle, which accepts the radius and name to its constructor. Implement the area and describe methods.

Properties can have getter and setter.

Class Equilateraltriangle:namedshape {    var sidelength:double = 0.0    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 Simp Ledescription (), String {        return "an equilateral triangle with sides of length \ (sidelength)."    }} var triangle = Equilateraltriangle (sidelength:3.1, Name: "a triangle") Triangle.perimetertriangle.perimeter = 9.9triangle.sidelength
   

In Perimeter's setter, the name of the new value is newvalue. You can provide a non-conflicting name after set.

Note that the Equilateraltriangle constructor has 3 different steps:

    1. Set the value of a property
    2. Calling the constructor of a super class
    3. Change the value of the properties defined by the superclass, add additional work to use the method, getter, setter can also be here

If you don't need to calculate the properties, but still provide the work after setting the value, use willset and didset . For example, the following class guarantees that the edge length of its triangle is equal to the length of the rectangle.

Class Triangleandsquare {    var triangle:equilatertriangle {    Willset {        square.sidelength = Newvalue.sidelength    }    }    var square:square {    Willset {        triangle.sidelength = Newvalue.sidelength    }    }    Init (size:double, name:string) {        square = Square (sidelength:size, name:name)        triangle = Equilatertriangle (s Idelength:size, Name:name)    }}var triangleandsquare = Triangleandsquare (size:10, Name: "Another Test shape") Triang LeAndSquare.square.sideLengthtriangleAndSquare.triangle.sideLengthtriangleAndSquare.square = Square (sidelength: Name: "Larger square") triangleAndSquare.triangle.sideLength

There is an important difference between the methods of a class and the function. The parameter name of the function is used only with the function, but the parameter name of the method can also be used to invoke the method (except for the first argument). By default, a method has a parameter with the same name, which is called the parameter itself. You can specify a second name to use inside the method.

Class Counter {    var count:int = 0    func incrementby (amount:int, Numberoftimes times:int) {        count + = Amount * Times    }}var counter = Counter () Counter.incrementby (2, Numberoftimes:7)

When working with an optional value, you can write "?" to the operator before it resembles the method property. If the value is in the "?" Before it was nil, all the "?" will be ignored automatically, and the whole expression is nil. In addition, the optional values are unpackaged, and all "?" are followed as unpackaged values. In both cases, the value of the entire expression is an optional value.

Let Optionalsquare:square? = Square (sidelength:2.5, name: "Optional square") Let Sidelength = Optionalsquare?. Sidelength
7 Enumerations and structs

Use enum to create an enumeration. Like classes and other named types, enumerations can have methods.

Enum Rank:int {case    aces = 1 Case    -Three, four, Five, Six, Seven, Eight, Nine, Ten case    Jack, Queen, King    func simpledescrition (), 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  //by Gasherolet Acerawvalue = Ace.toraw ()

Note

Practice

Write a function to compare the values of two Rank by comparing their original values.

In the above example, the original value is of type Int so you can specify only the first original value. The original values thereafter are assigned in order. You can also use a string or floating-point number as the original value for the enumeration.

Use the toraw and fromraw functions to convert original values and enumeration values.

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

The member value of an enumeration is the actual value, not the original value written in other ways. In fact, there are cases where the original value is the one you don't provide.

Enum Suit {case    spades, Hearts, Diamonds, Clubs    func simpledescription ()-String {        switch self {        cas E. Spades:            return "spades" case        . Hearts:            return "Hearts" Case        . Diamonds:            return "dismonds" Case        . Clubs:            return "Clubs"        }    }}let hearts = suit.hearts    //by gasherolet heartsdescription = Hearts.simpledescription ()

Note

Practice

Add a color method to Suit and return "black" at spades and clubs, and return "red" to Hearts and diamounds.

Note the two methods that refer to the Hearts member above: when assigned to the hearts constant, the enumeration member Suit.hearts is referenced by the full name because the constant has no explicit type. In switch, the enumeration passes. The Hearts reference, because the value of self is known. You can use the handy method at any time.

Create a struct body using a struct . Structs support many of the same behaviors as classes, including methods and constructors. A big difference is that the pass-through between the code is always copied (the value is passed), and the class is passing the reference.

struct Card {    var rank:rank    var suit:suit    func simpledescription () String {        return "the \ (Rank.sim Pledescription ()) of         (Suit.simpledescription ()) "    }}let threeofspades = Card (rank:. Three, suit:. Spades) Let threeofspadesdescription = Threeofspades.simpledescription ()

Note

Practice

Add a method to the card class to create a table of cards, each with a combined rank and suit. (It's a typist's job two, by Gashero).

An instance member of an enumeration can have the value of an instance. The same enumeration member instance can have different values. You assign a value when you create an instance. Specify the difference between the value and the original value: the original value of the enumeration is the same as its instance, and you provide the original value when you define the enumeration.

For example, suppose the situation requires that the sun rise and landing time be obtained from the server. The server can respond to the same information or some error message.

enum serverresponse {case Result (string, string) case Error (string)}let success = Server Response.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): Let Serverresponse = "Failure ... \ (Error)"} 

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.