Swift programming language Getting Started Tutorial

Source: Internet
Author: User
Tags constant definition sunrise and sunset times





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, the syntax looks familiar. In Swift, this is the complete program. You don't need to import a separate library for input and output and string processing. Global scope code is the entry point for your program, so you don't need to write a main () function. You also don't need to write a semicolon after each statement.

This primer will give you enough information to teach you a programming task. Don't worry if you don't understand something yet, everything that is not explained will be explained in detail later in this book.

Note

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

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

var myVariable = 42
myVariable = 50
let myConstant = 42
Note

gashero note

The constant definition here is similar to a variable in a functional programming language and cannot be modified after one assignment. A lot of use is good for your health.

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

Note

gashero note

Types are bound to variable names and belong to a statically typed language. Helps with static optimization. Different from Python, JavaScript, etc.

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 = 70
let imlicitDouble = 70.0
let explicitDouble: Double = 70
Note

Exercise

Create a constant of type Float with 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 required type.

let label = "The width is"
let width = 94
let widthLabel = label + String (width)
Note

Exercise

What error do you get when you try to delete the String conversion in the last line?

There is an easier way to include the value in the string: write the value in parentheses and use a backslash ("") before the parentheses. E.g:

let apples = 3
let oranges = 5 // by gashero
let appleSummary = "I have \ (apples) apples."
let fruitSummary = "I have \ (apples + oranges) pieces of fruit."
Note

Exercise

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

Create an array and dictionary using square brackets "[]" and access its elements by 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 as "[]" and an empty dictionary as "[:]". For example, you set a know variable and pass parameters 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, do-while as loops. Parentheses are not required, but braces of the body are required.

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score> 50 {
        teamScores + = 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 implicitly compared to 0.

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

var optionalString: String? = "Hello"
optionalString == nil

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \ (name)"
}
Note

Exercise

Change optionalName to nil. What happens when greeting? 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 braces is skipped. Otherwise the optional value is unwrapped and assigned a constant, which would be an unwrapped value variable into a code block.

The switch supports a variety of data and a variety of comparisons. There is no restriction on integers and tests being equal.

let vegetable = "red pepper"
switch vegetable {
case "celery":
    let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
    let vegetableComment = "That 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

Exercise

Try removing default and see what errors you get.

After executing the matched case, the program will jump out of the switch instead of continuing to the next case. So there is no longer a need to break out of switch.

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

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number> largest {
            largest = number
        }
    }
}
Note

Exercise

Add another variable to track which category has the largest number, which is where the largest number is.

Use while to repeatedly execute a block of code until the condition changes. The condition of the loop can be placed at the end to ensure that the loop is executed at least once.

var n = 2
while n <100 {
    n = n * 2
}
n

var m = 2
do {
    m = m * 2
} while m <100
m
You can keep an index in a loop, use ".." to indicate the index range or explicitly declare an initial value, condition, and increment. These two loops do the same thing:

var firstForLoop = 0
for i in 0..3 {
    firstForLoop + = i
}
firstForLoop

var secondForLoop = 0
for var i = 0; i <3; ++ i {
    secondForLoop + = 1
}
secondForLoop
Constructing a range with .. ignores the highest value, while constructing a range with ... contains two values.

5 Functions and closures
Use func to declare a function. The calling function uses his name plus the parameter list in parentheses. Use-> to separate the parameter name and return value type.

func greet (name: String, day: String)-> String {
    return "Hello \ (name), today is \ (day)."
}
greet ("Bob", "Tuesday")
Note

Exercise

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

Use tuples to return multiple values.

func getGasPrices ()-> (Double, Double, Double) {
    return (3.59, 3.69, 3.79)
}
getGasPrices ()
The function can accept the number of variable parameters and collect them 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

Exercise

Write a function to calculate the average of its parameters.

Functions can be nested. Embedded functions have access to variables whose functions they define. You can use inline functions to organize your code and avoid being too long and complicated.

func returnFifteen ()-> Int {
    var y = 10
    func add () {
        y + = 5
    }
    add ()
    return y
} // by gashero
returnFifteen ()
Functions are of the first type. This means that a function can return another function.

func makeIncrementer ()-> (Int-> Int) {
    func addOne (number: Int)-> Int {
        return 1 + number
    }
    return 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 numbers = [20, 19, 7, 12]
hasAnyMatches (numbers, lessThanTen)
Functions are actually special cases of closures. You can write a closure without a name, just place it in 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

Exercise

Rewrite a closure to return 0 for all odd numbers.

There are multiple options when writing closures. When the type of a closure is known, such as representing a callback, you can ignore its parameters and return value, or both. Closures of a single statement can return values directly.

numbers.map ({number in 3 * number})
You can refer to a parameter by number instead of name, which is useful for very short closures. A closure passes its last parameter to the function as the return value.

sort ([1, 5, 3, 12, 2]) {$ 0> $ 1}
6 Objects and classes
Use class to create a class. A property declaration is declared as a constant or variable in the class, except in the context of the class. Methods and functions are also written this way.

class Shape {
    var numberOfSides = 0
    func simpleDescription ()-> String {
        return "A shape with \ (numberOfSides) sides."
    }
}
Note

Exercise

Add a constant property via "let" and add another method that accepts parameters.

Create an instance of a class by placing parentheses after the class name. Use dot syntax to access the properties and methods of the instance.

var shape = Shape ()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription ()
Some important things about this version of the Shape class are missing: a constructor to set the class when creating an instance. Use init to create one.

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 that self is used to distinguish the name attribute from the name parameter. The life of a constructor is the same as a function, except that it creates an instance of the class. Each attribute needs to be assigned a value, either in the declaration or in the constructor.

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

Subclasses include the names of their superclasses, separated by colons. No declaration is required when inheriting from the standard root class, so you can ignore superclasses.

Subclass methods can override implementations in the superclass by marking override, and those without overrides will be treated as errors 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 \ (sideLength)."
    }
}

let test = Square (sideLength: 5.2, name: "my test square")
test.area ()
test.simpleDescription ()
Note

Exercise

Write another NamedShape subclass called Circle that accepts the radius and name into its constructor. Implement the area and describe methods.

Properties can have getters and setters.

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 simpleDescription ()-> String {
        return "An equilateral triangle with sides of length \ (sideLength)."
    }
}

var triangle = EquilateralTriangle (sideLength: 3.1, name: "a triangle")
triangle.perimeter
triangle.perimeter = 9.9
triangle.sideLength
In the perimeter setter, the name of the new value is newValue. You can provide a non-conflicting name after the set.

Note that the constructor of EquilateralTriangle has 3 different steps:

Set the value of a property
Call superclass's constructor
Change the value of the properties defined by the superclass, add additional work to use methods, getters, setters can also be here
If you don't need to calculate properties, but still want to provide work after setting values, use willSet and didSet. For example, the following class guarantees that the length of the sides of the triangle is equal to the variable 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 (sideLength: size, name: name)
    }
}
var triangleAndSquare = TriangleAndSquare (size: 10, name: "another test shape")
triangleAndSquare.square.sideLength
triangleAndSquare.triangle.sideLength
triangleAndSquare.square = Square (sideLength: 50, name: "larger square")
triangleAndSquare.triangle.sideLength
There is an important difference between class methods and functions. Function parameter names are only used with functions, but method parameter names can also be used to call methods (except for the first parameter). By default, a method has a parameter with the same name, and when called, it is the parameter itself. You can specify a second name and use it 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 optional values, you can write "?" Before the operator similar to a method attribute. If the value is already nil before "?", Everything after "?" Is automatically ignored, and the entire expression is nil. In addition, optional values are unwrapped, all after "?" Are unwrapped values. In both cases, the value of the entire expression is optional.

let optionalSquare: Square? = Square (sideLength: 2.5, name: "optional square")
let sideLength = optionalSquare? .sideLength
7 enums and structures
Use enums to create enums. Like classes and other named types, enums can have methods.

enum Rank: Int {
    case Ace = 1
    case Two, 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 gashero
let aceRawValue = ace.toRaw ()
Note

Exercise

Write a function that compares the values of two Ranks by comparing their original values.

In the example above, the type of the primitive value is Int so you can specify only the first primitive value. Subsequent primitive values are assigned sequentially. You can also use a string or floating point number as the primitive value of the enumeration.

Use the toRaw and fromRaw functions to convert raw and enumerated values.

if let convertedRank = Rank.fromRaw (3) {
    let threeDescription = convertedRank.simpleDescription ()
}
The member values of the enumeration are the actual values, not the original values written in other ways. In fact, some cases are primitive values, when you don't provide them.

enum Suit {
    case Spades, Hearts, Diamonds, Clubs
    func simpleDescription ()-> String {
        switch self {
        case .Spades:
            return "spades"
        case .Hearts:
            return "hearts"
        case .Diamonds:
            return "dismonds"
        case .Clubs:
            return "clubs"
        }
    }
}
let hearts = Suit.Hearts // by gashero
let heartsDescription = hearts.simpleDescription ()
Note

Exercise

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

Note the above two methods of quoting Hearts members: When assigning to the hearts constant, the enum member Suit.Hearts is referenced by full name because the constant has no explicit type. In the switch, the enumeration is referenced by .Hearts because the value of self is known. You can use the convenient method at any time.

Use struct to create a structure. Structures support many of the same behaviors as classes, including methods and constructors. One important difference is that code is always copied (passed by value), while classes are passed by reference.

struct Card {
    var rank: Rank
    var suit: Suit
    func simpleDescription ()-> String {
        return "The \ (rank.simpleDescription ()) of (suit.simpleDescription ())"
    }
}
let threeOfSpades = Card (rank: .Three, suit: .Spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription ()
Note

Exercise

Add methods to the Card class to create a table of cards, each of which has a combined rank and suit. (Just a typist's job, by gashero).

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

For example, suppose a situation requires the sun's rise and fall times to be obtained from a server. The server can respond to the same message or some error messages.

 
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 is at \ (sunrise) and sunset is at \ (sunset)."
case let .Error (error):
    let serverResponse = "Failure ... \ (error)"
}
Note

Exercise

Add a third case to ServerResponse to choose from.

Note that the sunrise and sunset times are actually selected from a partial match to ServerResponse.

 

Getting started with the Swift programming language

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.