A new modern language -- A Preliminary Study of swift

Source: Internet
Author: User

New language
In a brief introduction to WWDC, the new language Swift was launched. Although the name of the new language caused fans and developers to compete for the site, Yu Yan just came here.
In the WWDC keynote, Swift has many labels: closures, generics, namespaces, type inference, and multiple return types.
Closure, generic support, namespace, implicit type conversion, multiple return values, and other outstanding features make the language modern and convenient, in addition, I learned a lot of excellent syntaxes for other languages, such as go and Javascript. At the same time, it has high compilation performance and interactive scripting language, perhaps these are the reasons why Apple uses it to replace objective-C. This article provides a brief overview of frequently used syntaxes.
Simple assignment and Printing
Let L = "hello" // constant assignment, in swift ";" not necessary var v = "world" // variable assignment println (l) // use println for logprintln ("nihao \ (v)") // use \ () to format the output
Explicit declaration type

VaR STR: String = "nihao"


VaR numstr = "4"

VaR realnumber = 5

VaR sum = numstr + realnumber // The Compiler prompts an error because implicit type conversion is not supported.

When declaring a type, if there is no obvious life as a string, the compiler will also perform type deduction (type inference) and think it is of the string type. So after removing the disadvantages of OC in the type, let the error appear as soon as possible.
Optional
However, if we want to implement the above operation, we can actually implement it. here we need to introduce a new concept optional.
With "? ""! .
When we are not sure whether this value can be nil today or in the future, these symbols will be added at the end of the assignment or usage.

VaR nilstr: string? = "Nilornotnil"

Nilstr = Nil


In this way, it can be changed to nil. The default value assignment cannot be assigned to nil. Note that the NIL here is not the nil null pointer used in objective-C, but a niltype.
When we confirm that it is not empty, we can add "! "For example, we can use the string toint () function and "! "To complete the operation we want to perform. The code looks like this:

VaR numstr = "4"

VaR realnumber = 5


VaR sum = numstr. toint ()! + Realnumber



Array and dictionary Declaration

VAR numbers = [1, 5, 2, 1, 6]

VaR dict = ["isnew": "Yes ",

"Name": "Swift"]


Both data structures are represented by braces instead of braces, which can be separated from function flow control and closure.

Numbers [3] = 4


You can directly assign values to elements in the array without having to worry about mutable array or array.

Process control statement
For Loop and if statement

Numbers = [4, 5, 6, 7, 8, 9]

VaR largethanthree = 0

For N innumbers {

If n> 3 {

Largethanthree ++

} Else {

Largethanthree --

}

}

Largethanthree // 6


Key value can be obtained during dictionary traversal.

For (question, answer) Indict {

If question = "isnew "{

Answer // Yes

} Else {

Answer // swift

}

}


Pay attention to the use of optional in the IF statement.

VaR optionalstr: string? = "Swift"

VaR greeting: string? = "Nihao"

Optionalstr = Nil

If let name = optionalstr {

Greeting = "nihao, \ (name)" // does not run

}


However, if optionalstr is not assigned as nil, that is, it is still "Swift", the greeting variable is assigned as "nihao, Swift"


Switch statement

Swift switch supports case ratio of string

Let object = "water"

VaR Statement = "the object is"

Switch object {

Case "ice ":

Statement + = "ice"

Case "water", "other ":

Statement + = "water"

Default:

Statement + = "unknown"

}

Statement // "the object is water"


Break is no longer required here. Multiple matching codes are still separated by commas (,).


While statement

VaR big = int8.max // 127 maximum value of an integer of eight digits

While Big> 0 {

Big --

}


For

Write the common for loop in swift.

VaR loop = 0

For var I = 0; I <3; I ++ {

Loop ++

}

Loop // 3

Now swift supports a new syntax to complete such operations.

Loop = 0

For I in 0 .. 3 {

Loop ++

}

Loop // 3


Let us assume that I can use 0... 3 to replace 0... 3.


Function


Functions become very flexible in swift. They can support a single return value, return multiple values, or even nested functions, return functions, or use functions as the number of arguments.

Func sayhello (person name: String, weekday day: string)-> string {

Return "Hello \ (name), today is \ (day )"

}

VaR res = sayhello (person: "mattt", weekday: "Monday ")

-> As the return value symbol, the person before the name belongs to the number of arguments, and the value can be directly transmitted without being added. This is added for the convenience of functions.


Multiple return values of variable values

The data structure consisting of multiple values of different types or the same type is called tuple in swift)

Use the next function to input variable values and use tuples to return multiple values.

Func caculate (numbers: int...)-> (INT, INT ){

VaR nsum = 0

VaR navg = 0

For number in numbers {

Nsum + = Number

}

Nsum

Navg = nsum/numbers. Count

Return (nsum, navg)

}

VaR (S: int, A: INT) = caculate (1, 2, 3)

S // 6

A // 2


Nested Functions

Func funs (number: INT)-> int {

Var y = 10 + number

Func add (){

Y ++

}

Add ()

Return y

}


Functions can also be passed as return values.

Func makeincrementer ()-> (INT-> INT ){

Func addone (number: INT)-> int {

Return 1 + number

}

Return addone

}

VaR increment = makeincrementer ()

Increment (7)


Closure Functions

VAR numbers: int [] = [4, 3, 1, 2, 5]

Numbers. Map ({

(Number: INT)-> int in

Let result = 3 * Number

Return result

})



This blog introduces the preliminary use of SWIFT, which is expected to be pointed out in some improper ways.







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.