Introduction to the Swift programming language

  • 2020-05-07 20:31:02
  • OfStack

The original address: http: / / gashero iteye. com/blog / 2075324

directory

1 introduction to    
2 introduction to     Swift
3     simple value
4     control flow
5     functions and closures
6     objects and classes
7     enumeration and structure

1     introduction

Apple just released the Swift programming language in the early hours of this morning. I hope to help you with 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 secure programming modes and adds modern functionality to make programming easier, more flexible, and more fun. The interface, based on the popular Cocoa and Cocoa Touch frameworks, shows a new direction for software development.

The Swift has been around for years. Apple is based on existing compilers, debuggers, and frameworks as its infrastructure. Simplify memory management with ARC(Automatic Reference Counting, automatic reference counting). Our framework stack is 1 directly based on Cocoa. The Objective-C evolution supports blocks, collection literal, and modules, allowing the frameworks of modern languages to be used without going deep. Thanks to this foundation work, it was possible to introduce new programming languages into Apple software development.

The developers of Objective-C will feel the deja vu of Swift. Swift adopts the named parameters and dynamic object model of Objective-C. Provides interoperability with the Cocoa framework and mix-and-match. Based on these foundations, Swift introduces a number of new capabilities and combines both procedural and object-oriented capabilities.

Swift is also friendly to new programmers. It is an industrial-quality systems programming language, yet as friendly as a scripting language. It supports playground, allowing programmers to experiment with 1 piece of Swift code and see the results immediately without the hassle of building and running an application.

Swift integrates modern programming language ideas with the wisdom of the Apple engineering culture. Compilers are optimized for performance, while languages are optimized for development, without compromise. (by gashero) can be learned from "Hello, world" and transferred to the whole system. All this makes Swift a source of innovation for Apple software developers.

Swift is a fantastic way to write iOS and OSX applications and will continue to push the introduction of new features. We can't wait to see what you do with it.

2     Swift introduction

Learning a new language should begin by printing "Hello, world". In Swift, that's 1 row:

println("Hello, world")

If you have written C or Objective-C code, this syntax looks familiar, in Swift, this is the complete program. You do not need to import (import) a single library for input, output and string handling. Globally scoped code is the entry to the program, so you don't have to write an main() function. You also don't have to write a semicolon after every statement.

This primer will give you enough information to complete 1 programming task. Don't worry about what you don't understand. Anything you don't explain will be explained in more detail later in this book.

Note

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

3     simple value

Constants are defined using let, and variables are defined by var. The value of a constant need not be specified at compile time, but must be assigned at least once. This means that you can use a constant to name a value, and you find that you only need to do it once, but use it in more than one place.

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 that cannot be modified after one assignment. Use more is good for your health.

1 constant or variable must have the same type as when assigned. So you don't have to define the type strictly. Providing one value creates a constant or variable and lets the compiler infer its type. In the above example, the compilation would infer that myVariable is an integer type because its initialization value is an integer.

Note

gashero note

A type is bound to a variable name and belongs to a statically typed language. Helps with static optimization. It is different from Python, JavaScript, etc.

If the initialization value does not provide enough information (or does not initialize the 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

practice

Create 1 constant of type Float with a value of 4.

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


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

Note

practice

What errors do you get when you try to delete the String transform from the last 1 line?

There is an easier way to include a value in a string: write the value in parentheses, preceded by a backslash (""). Such as:


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

Note

practice

Use () to include a float to the string and to include someone's name to greet.

Create an array and dictionary using square brackets "[]" and access its elements through the index or key in the 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 "[:]".

shoppingList = []     // go shopping and buy something

4     control flow
USES if and switch as conditional controls. Use for-in, for, while, do-while as a loop. Braces are not required, but braces for the body are.


let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScores += 3
    } else {
        teamScores += 1
    }
}
teamScore

In the if statement, the condition must be a Boolean expression, which means if score {... } is false and cannot be implicitly compared to 0.

You can use if and let to prevent value loss. These values are optional. The optional value can contain one value or an nil to specify that the value does not yet exist. Write a question mark "?" Indicates that the value is optional after the type.


var optionalString: String? = "Hello"
optionalString == nil
 
var 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 someone? Add an else clause to set a different value when optionalName is nil.

If the optional value is nil, the condition is that the code in false braces is skipped. Otherwise, if the optional value is unwrapped and assigned to a constant, the unwrapped value of the variable will be added to the code block.

switch supports a variety of data as well as a variety of comparisons, with no restriction on the number of integers that must be equal to the test.


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

practice

Try removing default and see what you get.

After performing a match, the program jumps from switch instead of continuing with the next case. So you don't need break to jump out of switch.

You can use for-in to iterate over each element in the dictionary, providing 1 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

practice

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

Use while to execute blocks of code repeatedly until conditions change. Loop conditions 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 1 index in the loop by ".." To express the index range or explicitly declare an initial value, condition, or 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

Use.. The construction range ignores the highest value and USES... The constructed range contains two values.

5     functions and closures
declares 1 function using func. The calling function USES its name and a list of arguments in parentheses. Use - > Separates the name of the parameter from the return value type.


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

Note

practice

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

Use tuples (tuple) to return multiple values.


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

Function can accept the number of variable arguments collected 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. An embedded function can access the variables of the function it defines. You can use inline functions to organize your code without being too long or too complex.


func returnFifteen() -> Int {
    var y = 10
    func add() {
        y += 5
    }
    add()
    return y
}   //by gashero
returnFifteen()

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


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

1 function can accept other functions as arguments.


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

A function is really a special case of a closure. You can write a closure without a name, just in curly braces. Use in to return values for specific parameters and principals.


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

Note

practice

Override 1 closure to return 0 for all odd Numbers.

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

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

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

sort([1, 5, 3, 12, 2]) { $0 > $1 }

6     objects and classes
USES class to create one class. The declaration of an attribute 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.


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

Note

practice

Add a constant property through "let" and add another method to accept parameters.

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


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

This version of the Shape class has something important missing: a constructor to set the class when the instance is created. Use init to create one.


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

Note that self is used to distinguish the name attribute from the name parameter. The constructor has the same life as the function 1, except that it creates an instance of the class. Each property requires an assignment, either in the declaration or in the constructor.

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

The subclass includes the name of its superclass, separated by a colon. There is no need to declare when inheriting from the standard root class, so you can ignore the superclass.

Subclass methods can be implemented by marking override as overloaded in the superclass, while those without override are considered errors by the compiler. The compiler also checks for methods that are not overloaded.


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

Note

practice

Write another subclass of NamedShape called Circle, accepting 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 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 setter of perimeter, the name of the new value is newValue. You can provide 1 non-conflicting name after set.

Note that the EquilateralTriangle constructor has three different steps:

Sets the value of the property
Invokes the constructor of the superclass
Changing the value of the properties defined by the superclass, adding additional work to use the methods, getter, setter can also be used here
If you don't need to calculate the properties, but still need to provide work after setting the values, use willSet and didSet. For example, the following class has to make sure that the length of its three-angle side 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(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 a class method and a function. The argument name of a function is used only with the function, but the argument name of a method can also be used to call a method (except for the first argument). By default, a method has a parameter of the same name, which is itself when called. 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 the optional value 1, you can write "?" To the operator is similar to a method property. If the value is "?" It was already nil, all in "?" The rest is automatically ignored, and the whole expression is nil. Also, the optional values are unwrapped, all "?" Everything after that is an unwrapped value. 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     enumeration and structure
USES enum to create an enumeration. Like classes and other named types, enumerations 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

practice

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

In the example above, the primitive value is of type Int so you can specify only the first primitive value. The original values are then assigned in order. You can also use strings or floating point Numbers as the original values of an enumeration.

The original and enumerated values can be converted using the toRaw and fromRaw functions.


if let convertedRank = Rank.fromRaw(3) {
    let threeDescription = convertedRank.simpleDescription()
}

The member values of an enumeration are the actual values, not the original values written any other way. In fact, some cases are raw 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

practice

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

Note the two ways in which the Hearts member is referenced above: when assigned to an hearts constant, the enumeration member Suit.Hearts is referenced by the full name, because the constant has no explicit type. In 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 the structure. Structs support many of the same behaviors as classes, including methods and constructors. The big difference is that code always passes between copies (value passes), while classes pass references.


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

Note

practice

Add methods to the Card class to create 1 table of CARDS, each of which has a combined rank and suit. (it's a typist's job.)

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

For example, suppose you need to get the sunrise and sunset times from the server. The server can respond to the same message or an error message.


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

practice

Add a third case to ServerResponse to select.

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


Related articles: