Apple launches the new programming language Swift Introduction and introductory tutorials _ios

Source: Internet
Author: User
Tags arrays closure inheritance

First, what is Swift?

Swift is Apple's programming language in WWDC 2014, quoted by the Swift programming language:

Copy Code code as follows:

Swift is a new programming language for IOS and OS X apps that builds on the best C and objective-c, without the Constr Aints 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 in touch with frameworks, is a opportunity to imagine Ho W Software Development works.
Swift is the industrial-quality systems programming language This is as expressive and enjoyable as a scripting Lang Uage.

To put it simply:
Swift is used to write iOS and OS X programs. (It is not expected to support other cock-wire systems)
Swift absorbs the benefits of C and objective-c and is more powerful and easy to use.
Swift can use the existing cocoa and cocoa touch framework.
Swift has both the high performance (performance) and scripting language interactivity (Interactive) of the compiled language.

Ii. Overview of Swift language

1. Basic Concepts

Note: This section of code originates from Swift Tour in the swift programming language.

1.1.Hello, World

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

Copy Code code as follows:

println ("Hello, World")

1.2. Variables and constants

Swift uses VAR to declare a variable, let declare a constant.

Copy Code code as follows:

Ar myvariable = 42
myvariable = 50
Let myconstant = 42

1.3. Type deduction

Swift supports type inference, so the above code does not need to specify a type, if you need to specify the type:

Copy Code code as follows:
Let explicitdouble:double = 70

Swift does not support implicit type conversions (implicitly casting), so the following code requires an explicit type conversion (explicitly casting):

Copy Code code as follows:

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


1.4. String formatting

Swift uses the form of (item) for string formatting:

Copy Code code as follows:

Let apples = 3
Let oranges = 5
Let applesummary = "I have (apples) apples."
Let applesummary = "I have (apples + oranges) pieces of fruit."


1.5. Arrays and dictionaries

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

Copy Code code as follows:

var shoppinglist = ["Catfish", "water", "tulips", "Blue paint"]
SHOPPINGLIST[1] = "Bottle of Water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "public Relations"

You typically use the initializer (initializer) syntax to create an empty array and an empty dictionary:

Copy Code code as follows:

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

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

2. Control Flow

2.1 Overview

Swift's conditional statement contains if and switch, the loop statement contains For-in, for, while, and Do-while, and the loop/Judge condition does not require parentheses, but the circular/judgmental (body) required bracket:

Copy Code code as follows:

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 types

Combined with if and let, the nullable variable can be easily handled (nullable variable). For null values, it needs to be added after the type declaration. explicitly indicate that the type is nullable.

Copy Code code as follows:

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

The switch in Swift supports a variety of comparison operations:

Copy Code code as follows:

Let vegetable = "red pepper"
Switch Vegetable {
Case "Celery":
Let vegetablecomment = "Add some raisins and make ants on a log."
Case "cucumber", "watercress":
Let vegetablecomment = "This would make a good tea sandwich."
Case Let X where X.hassuffix ("Pepper"):
Let vegetablecomment = "is it a spicy (x)?"
Default
Let vegetablecomment = "Everything tastes good in soup."
}

2.4 Other cycles

For-in can also be used to traverse a dictionary in addition to traversing an array:

Copy Code code as follows:

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
}
}
}
Largest

While loops and Do-while loops:

Copy Code code as follows:

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, in addition to the combination. (Generate an interval) and for-in implement the same logic.

Copy Code code as follows:

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 also... :.. Generate a front-closed interval, and ... Generate the interval of the front closed back closure.

3. Functions and closures

3.1 function

Swift uses the FUNC keyword to declare functions:

Copy Code code as follows:

Func greet (name:string, day:string)-> String {

Return "Hello" (name), which is the day.

}
Greet ("Bob", "Tuesday")

Return multiple values through a tuple (Tuple):

Copy Code code as follows:

Func getgasprices ()-> (double, double, double) {
Return (3.59, 3.69, 3.79)
}
Getgasprices ()

Supports functions with variable-length parameters:

Copy Code code as follows:

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

Functions can also nest functions:

Copy Code code as follows:

Func returnfifteen ()-> Int {
var y = 10
Func Add () {
Y + 5
}
Add ()
Return y
}
Returnfifteen ()

As a first class object, a function can be passed either as a return value or as a parameter:

Copy Code code as follows:

Func makeincrementer ()-> (int-> int) {
Func AddOne (number:int)-> Int {
Return 1 + number
}
Return AddOne
}

var increment = Makeincrementer ()
Increment (7)

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)

3.2 Closures

Essentially, a function is a special closure, and Swift can declare an anonymous closure by using {}:

Copy Code code as follows:

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

When the type of closure is known, you can use the following simplified notation:

Copy Code code as follows:

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

In addition, you can use parameters by the position of the parameter, when the last parameter of the function is closed, you can use the following syntax:

Copy Code code as follows:
Sort ([1, 5, 3, 2]) {$ >}

4. Classes and objects

4.1 Creating and using classes

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

Copy Code code as follows:

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.





Copy Code code as follows:

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

Building objects from Init can either explicitly refer to the Member field (name) with self or implicitly reference (Numberofsides).

Copy Code code as follows:

Class Namedshape {
var numberofsides:int = 0
var name:string
Init (name:string) {
Self.name = Name
}
Func simpledescription ()-> String {
Return "A shape with (numberofsides) sides."
}
}


Use Deinit for cleanup work.

4.2 Inheritance and polymorphism

Swift supports inheritance and polymorphism (override parent-class methods):

Copy Code code as follows:

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 Properties

To simplify the code, Swift introduces the properties, see the following perimeter field:

Copy Code code as follows:



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 ()-&gt; String {


Return "A 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 assignment (setter), the received value is automatically named NewValue.

4.4willSet and Didset

The Equilateraltriangle constructor has the following actions:
1. Assign a value to a property of a subtype.
2. Invoke the constructor of the parent type.
3. Modify the properties of the parent type.
If you do not need to compute the value of the property, but you need to do something before and after the assignment, use Willset and Didset:

Copy Code code as follows:



Class Triangleandsquare {


var Triangle:equilateraltriangle {


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 = Equilateraltriangle (sidelength:size, Name:name)


}


}


var triangleandsquare = Triangleandsquare (size:10, Name: "Another Test shape")


TriangleAndSquare.square.sideLength


Triangleandsquare.square = Square (sidelength:50, name: "Larger square")


TriangleAndSquare.triangle.sideLength


So as to ensure that triangle and square have equal sidelength.

4.6 Calling methods

In Swift, the parameter name of a function can only be used inside a function, but the parameter name of the method is externally available in addition to internal use (except for the first parameter), for example:

Copy Code code as follows:

Class Counter {
var count:int = 0
Func IncrementBy (Amount:int, Numberoftimes times:int) {
Count + = Amount * times
}
}
var counter = counter ()
Counter.incrementby (2, Numberoftimes:7)

Note that Swift supports aliases for method parameters: In the above code, Numberoftimes faces the outside, and the times is inward-facing.

Another use of 4.7?

When you use a nullable value, you can appear in front of a method, property, or subscript. If the previous value is nil, then the following expression is ignored, and the original expression returns directly to nil, for example:

Copy Code code as follows:
Let Optionalsquare:square? = Square (sidelength:2.5, Name: "Optionalsquare")
Let Sidelength = Optionalsquare? Sidelength

When Optionalsquare is nil, the Sidelength property call is ignored.

5. Enumeration and structure

5.1 Enumeration

Create an enumeration with an enum--note that Swift's enumeration can associate 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 ()

Use Toraw and Fromraw to convert between raw (raw) values and enumerated values:

Copy Code code as follows:

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

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

In some cases the enumeration does not have a meaningful original value, the original value can be ignored directly:

Copy Code code as follows:



Enum Suit {


Case Spades, Hearts, diamonds, clubs


Func simpledescription ()-&gt; String {


Switch Self {


Case. Spades:


Return "Spades"


Case. Hearts:


Return "Hearts"


Case. Diamonds:


Return "Diamonds"


Case. Clubs:


Return "clubs"


}


}


}


Let hearts = Suit.hearts


Let heartsdescription = Hearts.simpledescription ()



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:


Copy Code code as follows:

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)"
}

5.2 Structure

Swift uses the struct keyword to create a structure. Structs support the attributes of these classes of constructors and methods. The biggest difference between structs and classes is that an instance of a struct is passed by value (passed by) and an instance of the class is passed by reference (passed by reference).

Copy Code code as follows:

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 ()

5.3 Protocol (Protocol) and Extension (extension) protocol

Swift uses protocol to define the protocol:

Copy Code code as follows:

Protocol Exampleprotocol {
var simpledescription:string {Get}
Mutating func adjust ()
}



Types, enumerations, and structs can all implement the (adopt) protocol:


Copy Code code as follows:

Class Simpleclass:exampleprotocol {
var simpledescription:string = "A very simple class."
var anotherproperty:int = 69105
Func Adjust () {
Simpledescription = "Now 100% adjusted."
}
}
var a = Simpleclass ()
A.adjust ()
Let adescription = A.simpledescription
struct Simplestructure:exampleprotocol {
var simpledescription:string = "A Simple Structure"
Mutating func adjust () {
Simpledescription + = "(adjusted)"
}
}
var B = simplestructure ()
B.adjust ()
Let bdescription = B.simpledescription






5.4 Expansion

Extensions are used to add new functionality (such as new methods or attributes) to an existing type, and Swift uses the extension declaration extension:

Copy Code code as follows:

Extension Int:exampleprotocol {
var simpledescription:string {
Return "the number" (self)
}
Mutating func adjust () {
Self = 42
}
}
7.simpleDescription

5.5 Generics (generics)

Swift uses <> to declare a generic function or generic type:

Copy Code code as follows:

Func repeat<itemtype> (Item:itemtype, Times:int)-> itemtype[] {
var result = itemtype[] ()
For I in 0..times {
Result + = Item
}
return result
}
Repeat ("Knock", 4)

Swift also supports the use of generics in classes, enumerations, and structs:

Copy Code code as follows:

Reimplement the Swift standard library ' s optional type
Enum Optionalvalue<t> {
Case None
Case Some (T)
}
var possibleinteger:optionalvalue<int> =. None
Possibleinteger =. Some (100)






Sometimes you need to do something about generics (requirements), such as requiring that a generic type implement an interface or inherit from a particular type, that two generic types belong to the same type, and so on, where Swift describes these requirements by:


Copy Code code as follows:

Func anycommonelements <t, U where t:sequence,
U:sequence, T.generatortype.element:equatable,
T.generatortype.element = = u.generatortype.element> (lhs:t, rhs:u)-> Bool {
For Lhsitem in LHS {
For Rhsitem in RHS {
if Lhsitem = = Rhsitem {
return True
}
}
}
return False
}
Anycommonelements ([1, 2, 3], [3])

Swift Language overview Here, interested friends please read the Swift programming Language further.

Next, let's talk about some of the personal feelings about Swift.

Personal feelings

Note: The following feelings are purely personal opinions, for reference only.

Hodgepodge

Although I am less than two hours in touch with Swift, it is easy to see that Swift absorbs a number of elements from other programming languages, including but not limited to:

Properties, nullable values (Nullable type) syntax, and generic (Generic type) syntax are derived from C #. The format style is similar to go (no semicolon at the end of the sentence, no parentheses are required to determine the condition). Python-style Current instance reference syntax (using self) and list Dictionary declaration syntax. Haskell-style interval declaration syntax (for example, 1. 3,1 ... 3). Protocols and extensions originate from objective-c (their own products are used casually). Enum types are much like Java (you can have members or methods). The concept of class and struct is very similar to C #.

Note that this is not to say that Swift is plagiarism--in fact, the pattern that programming languages can play is basically the case, and Swift chooses the features that seem pretty good to me.

Moreover, the benefit of this hodgepodge is that it is important that no other programming language developer feels Swift is unfamiliar.

Reject implicit (refuse implicity)

Swift has removed some implicit operations, such as implicit type conversions and implicit method overloads. These two pits are pretty dry.

The direction of Swift's application

I think Swift has the following two main directions of application:

1. Education

I'm talking about programming education. The biggest problem with existing programming languages is the singularity of interactivity, which leads to steep learning curves. It is believed that Swift and its highly interactive programming environment can break this situation and allow more people-especially teenagers-to learn to program.

It is necessary to refer again to Brec Victor's inventing on principle, and to see this video you will understand what a highly interactive programming environment can bring.

2. Application Development

The existing iOS and OS X applications are developed using OBJECTIVE-C, while Objective-c is a cumbersome (verbose) language with a steep learning curve, and if Swift can provide a simple interoperability interface with the existing OBJ-C framework, I believe that there will be a large number of programmers to go to Swift, and at the same time Swift's simple syntax will bring a significant number of other platform developers.

In short, the last time a big company launched a High-profile programming language and its programming platform in 2000 (Microsoft launched C #), nearly 15 years later, Apple launched swift--as a developer, I am happy to witness the birth of a 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.