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.

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
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 sum }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]) {$ > $}
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 = Serverresponse.result ("6:00 Am "," 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)"}

Note

Practice

Add a third case to Serverresponse to choose.

more details

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.