1. Swift syntax Overview

Source: Internet
Author: User
Tags switch case

SWIFT is Apple's latest language used to write iOS and OS X programs. It is compatible with C and objective-C. Some examples in this series of articles are from Apple's official guide: the swift programming language. If you are interested, you can download the original English iBook from Apple's official website.

1. Hello World

In swift, the main function is neither required nor used. Separate the statements for each row. A simple hello World statement is as follows:

println("Hello, world")

Ii. Assignment

Use let to create a constant and VaR to create a variable, as shown below:

var myVariable = 42myVariable = 50let myConstant = 42

If the initial value does not provide enough type information, use a colon to define the variable type:

let implicitInt = 72let implicitDouble = 72.0let explicitDouble : Double = 72

As shown above, variables can be implicitly defined or explicitly defined using colons.

However, variables outside of initialization will never be implicitly converted. For example, there are variables:

let label = "number is "let num = 5

The following statement is incorrect:

let numLabel = label + num

The reason is that the string cannot be added together with the integer type, so the correct syntax should be:

let numLabel = label + String(num)

There is a simpler way to include the value to be converted, that is, to use the backslash \ in double quotation marks to get the variable's string value:

let numLabel = "number is \(num)"

You can use square brackets [] to create dictionaries and arrays:

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

Use the initialization tool to create a blank dictionary or list:

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

When an array or type value can be inferred, [] can be used to represent a blank array, and [:] can be used to represent a blank dictionary.

3. Process Control


1. If and switch case condition Control

If and switch conditions do not require parentheses, and the case in the switch statement does not require break, because the statements in the case do not jump to the next case. For example:

Let Hello = "hello" Switch Hello {Case "hello": Let lang = "English" case "hello": Let lang = "Chinese" default: let lang = "other"} Let score = 62if score> = 60 {Let result = "passed"} else {Let result = "No pass "}

The condition in the IF statement must be a Boolean value, instead of passing 0 and non-0 as in the C language.


2. For, for-in, while, do while loop control

You do not need to add parentheses for the conditions in the loop statement. When a pair of values is used in the for-in statement, you can iterate the keys and values of the dictionary. For example, the following code returns the maximum value in the dictionary:

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

You can use... <in the for statement to simplify code writing. The following are two equivalent codes:

for i in 0..<4{ }for var i=0; i < 4; ++i { }

Iv. Functions and closures

Use func to define a function and use-> to indicate the return type of the function. It is similar to the post-return type of the function in C ++ 11. Function participate types are directly separated by colons, and form participate parameters are separated by commas.

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

You can use tuple to make the function return multiple values:
func getNumber() -> (Double, Double) {    return (1.0, 2.0)}

You can use... to receive parameters with an indefinite length. These parameters are used as a list:

func sumOf(numbers: Int...) -> Int {    var sum = 0;    for number in numbers {        sum += number    }}sumOf()sumOf(1,3,100)

Functions can be nested. nested functions can access the variables of external functions:

func test() -> Int {    var x = 10    func add(){        x += 5    }    add()    return x}

A function is also a type. For example, we can let a function return another function and call it.

func makeIncrement() -> (Int -> Int) {    func increase(number: Int) -> Int {        return number + 1    }    return increase}

As shown above, makeincrement returns a function that accepts an int parameter and returns an int value. In C ++, if a function is to be returned, the address of the function is generally returned. in C #, we can use the nested function as a Lambda expression to return the function, you can also return the delegate of a function.

Similarly, the form parameter of a function can also be a function:

func equals (numberA: Int, numberB: Int, equals: (Int, Int) -> Bool ) -> Bool {    return equals(numberA, numberB)}

Swift supports anonymous functions. You can regard an anonymous function as a variable, but it can be called. An anonymous function cannot contain a function name and must use in to separate the function signature and function body:

object.save({    (number: Int) -> Int in    let result = 3 * number    return result    })

V. Categories and objects

Use the class keyword to create a class. You can add variables, constants, and methods to the class)

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

As in Object-Oriented Programming, "." is used to access members in objects.

var shape = Shape()shape.numberOfSides = 7

Use the init method to create a constructor for the class and deinit to create a constructor for the class.

Like C ++ and C #, adding a colon to the class name can represent the inheritance of the class. To override a base class method, you must add the keyword override. If the base class method is accidentally overwritten without override, the compiler reports an error.

class A{    func test(){}}class B : A{    override func test(){}}

Like C #, you can define attributes in the class and write their get and set methods:

class A{    var _property : String = ""    var property : String{        get{            return "hello " + _property        }        set{            _property = newValue        }    }}

When assigning a value to a property, the set method is called, and the get method is called when the value is set. Newvalue in the set method indicates the value assigned to the property.

In addition, swift also defines two Property Methods: willset and didset, which respectively represent the methods before and after attribute assignment.

In swift, func in a class is called "method". A method can be a value in a member of a class:

class Counter {    var count: Int = 0    func add() {        count++    }}

6. Enumeration

Use the enum keyword to create an enumeration type and use case to define its enumerated values. The enumeration type can be regarded as a class because it can contain its own method. When calling its own method, one uses self to obtain its own information:

enum Rank: Int {    case Ace = 1    case Two, Three, Four    func description() -> String {        switch self {            case .Ace:                return "ace"            default:                return String(self.toRaw())        }    }}

As shown above, we have defined the enumerated type rank and defined its original type as int for it. If the original type is not important, you can also leave it blank, that is, remove ": int". In this case, you cannot assign an initial value to the enumeration member.

When the compiler can infer the type of an enumeration object, it does not have to add an enumeration type name when assigning values. For example, you can simplify rank. Ace to. Ace.

Enumeration members can even include parameters:

enum ServerResponse{    case Success(String)    case Error(String)}let error = ServerResponse.Error("Password incorrect!")

VII. Structure

Use the keyword struct to create a structure. Unlike the "class", the structure is passed by value during transmission, while the copy is passed by reference. See value transfer and reference transfer in C # and Java.

VIII. Agreement

The Protocol is like "interface" in C # and Java )":

protocol Example{    var description: String { get }    mutating func adjust()}

All classes and structures that inherit this Protocol must implement the get method of the description attribute and the adjust method.

In the structure, to implement the adjust method, you must add the keyword mutating before, indicating that it will change the value of its internal members, and the class itself can change the value of its own members, so you do not need to add it:

class ClassWithDescription : Example {    var description: String= "very simple"    func adjust(){        description=""    }}struct StructWithDescription : Example {    var description: String= "very simple"    mutating func adjust(){        description=""    }}

As with object-oriented design, you can use the example type to define any objects that inherit the example protocol, but it only contains the details in the example protocol.

9. Expansion

Like the Extension Method in C # And the class in objective-C, you can use the extension keyword to add extended attributes and methods for a known type.

extension Int: Example{    ....}extension Int{    ....}

10. Generic

Swift includes generic functions, generic methods, generic structures, generic enumeration, and generic structures. The generic type is written in angle brackets:

func repeat<ItemType>(item: ItemType, times: Int) -> [ItemType] {    var result = [ItemType]()    for i in 0..<times{        result += item    }    return result}repeat ("knock", 4)

You can add the WHERE clause to constrain generics:

func test<T where T: Sequence> (arg: T){    ....}

11. Summary

The above lists some of the syntax points of swift. It can be seen that SWIFT has learned from many successful language experiences: such as dynamic and random JavaScript, C # Attribute mechanism, generic mechanism, Java enumeration mechanism, and C ++ 11 Post-type return, it also simplifies the writing of the For Loop (which may be learned from Perl) and makes it a real object-oriented Dynamic Language.

After that, I will sort out every detail in the swift language and hope to learn with you.

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.