Introduction and introduction to Swift apple's new programming language

  • 2020-05-06 11:42:08
  • OfStack

What is Swift?

Swift is a programming language released by apple in WWDC 2014. The Swift Programming Language is quoted as


Swift is a new programming language for iOS and OS X apps that builds on the best of C and Objective-C, without the constraints of C compatibility.
Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible and more fun.
Swift's clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to imagine how software development works.
Swift is the first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language.

Simply put:
Swift is used to write iOS and OS X programs. (it is not expected to support other filaments.)
The Swift takes advantage of the C and Objective-C, and is more powerful and easy to use.
Swift can use the existing Cocoa and Cocoa Touch frameworks.
Swift combines the high performance of a compiled language (Performance) with the interactivity of a scripting language (Interactive).

language overview

1. Basic concept

Note: the code in this section is derived from A Swift Tour in The Swift Programming Language.

1.1.Hello, world

Similar to scripting languages, the following code is a complete Swift program.


println("Hello, world")

1.2. Variables and constants

Swift declares variables using var, and let declares constants.


ar myVariable = 42
myVariable = 50
let myConstant = 42

1.3. Type derivation

Swift supports type derivation (Type Inference), so the code above does not need to specify a type, if it does:

let explicitDouble : Double = 70

Swift does not support implicit type conversions (Implicitly casting), so the following code requires explicit type conversions (Explicitly casting) :


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


1.4. String formatting

Swift USES the form (item) for string formatting:


let apples = 3
let oranges = 5
let appleSummary = "I have (apples) apples."
let appleSummary = "I have (apples + oranges) pieces of fruit."


1.5. Array and dictionary

Swift USES the [] operator to declare arrays (array) and dictionaries (dictionary) :


var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

An empty array and an empty dictionary are typically created using the initializer (initializer) syntax:


let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()

If the type information is known, you can declare an empty array using [] and an empty dictionary using [:].

2. Control flow

2.1 overview

The conditional statement of Swift contains if and switch, the loop statement contains for-in, for, while and do-while, the loop/judgment condition does not require parentheses, but the loop/judgment body (body) requires parentheses:


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

2.2 nullable type

Combining if and let makes it easy to handle nullable variables (nullable variable). For null values, need to be added after the type declaration? Explicitly indicates that the type is nullable.


var optionalString: String? = "Hello"
optionalString == nil
var optionalName: String? = "John Appleseed"
var gretting = "Hello!"
if let name = optionalName {
    gretting = "Hello, (name)"
}

2.3 flexible switch

switch in Swift supports a variety of comparison operations:


println("Hello, world")
0

2.4 other cycles

Es260en-in can also be used to traverse dictionaries in addition to traversal groups:


println("Hello, world")
1

while cycle and do-while cycle:


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

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

Swift supports the traditional for loop, as well as by combining.. (generates an interval) and for-in implement the same logic.


var firstForLoop = 0
for i in 0..3 {
    firstForLoop += i
}
firstForLoop
var secondForLoop = 0
for var i = 0; i < 3; ++i {
    secondForLoop += 1
}
secondForLoop

Note: Swift except.. And... :.. Generate a closed and open interval, and... Generate a closed and closed interval.

3. Functions and closures

3.1 function

Swift declares the function
using the func keyword


println("Hello, world")
4

Returns multiple values via tuples (Tuple) :


println("Hello, world")
5

Support for functions with variable length arguments:


println("Hello, world")
6

Functions can also be nested:


println("Hello, world")
7

As first-class objects, functions can be passed either as return values or as arguments:


println("Hello, world")
8

3.2 closure

Essentially, functions are special closures, and in Swift you can declare anonymous closures with {} :


println("Hello, world")
9

When the type of closure is known, the following simplified notation can be used:


ar myVariable = 42
myVariable = 50
let myConstant = 42
0

You can also use arguments by their location, using the following syntax when the last argument to a function is a closure:

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

4. Classes and objects

4.1 create and use the

class

Swift USES class to create a class that can contain fields and methods:


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


Create an instance of the Shape class and call its fields and methods.


var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

Objects can be built with init, either explicitly referencing the member field (name) or implicitly (numberOfSides) using self.


class NamedShape {
    var numberOfSides: Int = 0
    var name: String
    init(name: String) {
        self.name = name
    }
    func simpleDescription() -> String {
        return "A shape with (numberOfSides) sides."
    }
}


Clean up using deinit.

4.2 inheritance and polymorphism

Swift supports inheritance and polymorphism (override superclass methods) :


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: if the simpleDescription method here is not identified as override, a compilation error will be thrown.

4.3 property

to simplify the code, Swift introduces properties (property), see the perimeter field below:


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 triagle with sides of length (sideLength)."
    }
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
triangle.perimeter
triangle.perimeter = 9.9
triangle.sideLength


Note: in the valuer (setter), the received value is automatically named newValue.

4.4willSet and didSet

The EquilateralTriangle constructor does the following:
1. Assign values to attributes of subtypes.
2. Invoke the constructor of the parent type.
3. Modify the properties of the parent type.
willSet and didSet:
are used if you do not need to calculate the value of the property, but you need to do something before and after the assignment


ar myVariable = 42
myVariable = 50
let myConstant = 42
7

So that triangle and square have the same sideLength.

4.6 calls the method

In Swift, the parameter names of functions can only be used inside functions, but the parameter names of methods can be used outside as well as inside (except for the first parameter), for example:


ar myVariable = 42
myVariable = 50
let myConstant = 42
8

Note that Swift supports aliasing method parameters: in the above code, numberOfTimes faces the outside and times faces the inside.

4.7? Another use of

With nullable values,? It can appear before methods, properties, or subscripts. If? The previous value is nil, so? The following expression is ignored, and the original expression returns nil directly, for example,

let optionalSquare: Square? = Square(sideLength: 2.5, name: "optionalsquare")
let sideLength = optionalSquare?.sideLength

When optionalSquare is nil, the sideLength attribute call is ignored.

5. Enumeration and structure

5.1 enumerates

Create an enumeration using enum -- note that the enumeration of Swift can be associated with methods:

enum Rank: Int {

      case Ace = 1

      case Two, 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"

              }
      }
}
let ace = Rank.Ace
let aceRawValue = ace.toRaw()

Convert between original (raw) values and enumerated values using toRaw and fromRaw:

let explicitDouble : Double = 70
0

Note that the member value in the enumeration (member value) is the actual value (actual value) and is not necessarily associated with the original value (raw value).

In some cases where the enumeration does not have a meaningful original value, you can simply ignore the original value:

let explicitDouble : Double = 70
1
In addition to associating methods, enumerations also support associating values on their members, and different members of the same enumeration can have different associated values:
let explicitDouble : Double = 70
2

5.2 structure

Swift creates the structure using the struct keyword. Structures support the properties of classes such as constructors and methods. The biggest difference between a structure and a class is that an instance of a structure is passed by value (passed by value), while an instance of a class is passed by reference (passed by reference).

let explicitDouble : Double = 70
3

5.3 protocol (protocol) and extension (extension) protocol

Swift defines the protocol using protocol:

let explicitDouble : Double = 70
4
Types, enumerations, and structures can all be implemented (adopt) protocol:
let explicitDouble : Double = 70
5

5.4 extends

Extensions are used to add new functionality (such as new methods or properties) to existing types, and Swift declares an extension:
using extension

let explicitDouble : Double = 70
6

5.5 generic (generics)

Use Swift < > To declare a generic function or generic type:

let explicitDouble : Double = 70
7

Swift also supports the use of generics in classes, enums, and structures:

let explicitDouble : Double = 70
8

Sometimes there are requirements for generics (requirements), such as requirements that a generic type implement an interface or inherit from a particular type, that two generic types belong to the same type, etc. Swift describes these requirements through where:
let explicitDouble : Double = 70
9

This is the end of the Swift language overview. If you are interested, please read The Swift Programming Language.

Here are some personal feelings about Swift.

personal feelings

Note: the following comments are personal and for reference only.

hodgepodge

Although I've been exposed to Swift for less than two hours, it's easy to see that Swift has absorbed a lot of elements from other programming languages, including, but not limited to,

The syntax for attributes (Property), nullable values (Nullable type), and generics (Generic Type) are derived from C#. The formatting style is similar to Go (no semicolons at the end of the sentence, no parenthesis required for judging conditions). Current instance reference syntax (using self) and list dictionary declaration syntax in the Python style. Haskell style interval declaration syntax (e.g. 1.. 3, 1... 3). Protocols and extensions from Objective-C. Enumeration types are much like Java (you can have members or methods). The concepts of class and struct are very similar to C#.

Note that this is not to say that Swift is a copycat -- in fact, there's only so much a programming language can do, and Swift selects features that I think are pretty good.

Also, it's important to note that this hodgepodge has the advantage that Swift is not alien to developers of any other programming language.

rejects implicit (Refuse implicity)

Swift does a good job of removing some implicit operations, such as implicit type conversion and implicit method overloading.

The application direction of Swift is

I think Swift mainly has the following two application directions:

1. Educate

I'm talking about programming education. The biggest problem with existing programming languages is the oddity of interactivity, which leads to a steep learning curve. Believe that Swift and its highly interactive programming environment can break this situation, let more people, especially teenagers, learn to code.

It's important to mention Brec Victor Inventing on Principle again, and watch this video to see what an interactive programming environment can do.

2. Application development

The existing iOS and OS X application development use Objective-C, and Objective-C is a very tedious language (verbose) with a steep learning curve, if Swift can provide a simple interop interface with the existing Obj-C framework, I believe that a large number of programmers will switch to Swift. At the same time, Swift's simple syntax will lead to a significant number of other platform developers.

Anyway, the last time a major company launched a programming language and its programming platform with much fanfare was in 2000 (Microsoft launched C #), and nearly 15 years later, apple launched Swift -- as a developer, I'm happy to witness the birth of a programming language

 


Related articles: