Some keywords in Swift

Source: Internet
Author: User

The following keywords reference passing parameters, attributes, modifying member variables, static variables, indexes, and constructor Overloading

Anyone who has read The Swift Programming Language can see that all of The above statements are not apple's idioms. The reason for this problem is that many of them have recently been transferred to swift, but they are not ios developers and are not used to apple. When searching others' blogs, they often get confused about simple problems because some nouns have different expressions. Just like the strange message and protocol statement when I first came into contact with oc, because my mother programming language can be called C #, and I prefer parameter and interface.

 

Next, let's use a few simple keywords to explain the several key words in swift that may give you a few minutes of thinking, but they are quite simple syntax.

 

I. in-out

Here, when in-out is used as a function declaration, the keyword of the passed value is referenced. It is equivalent to ref and out in C # and Java. However, when calling a function, you need to write an "&" symbol before the parameter.

Run the following code:

func swapTwoInts(inout a: Int, inout b: Int) {    let temporaryA = a    a = b    b = temporaryA}var someInt = 3var anotherInt = 107swapTwoInts(&someInt, &anotherInt)println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")

This is an instance in The Swift Programming Language and exchanges two values.

2. get set and willSet didSet

People familiar with C # can see at a glance what get set means, as shown in the following code. This method can simplify our work:

struct AlternativeRect {    var origin = Point()    var size = Size()    var center: Point {    get {        let centerX = origin.x + (size.width / 2)        let centerY = origin.y + (size.height / 2)        return Point(x: centerX, y: centerY)    }    set {        origin.x = newValue.x - (size.width / 2)        origin.y = newValue.y - (size.height / 2)    }    }}

For the sake of simplicity, we also use @ lazy to assign values to attributes after initialization.

class Head{
    var eyes = "eyes"
    var nose = "Nose"
}
class Arm{
    var hands = "hands"
}
class Human{
    @lazy var head = Head()
    @lazy var arm = Arm()
}

var human = Human()
var newhead = Head()
newhead.eyes = "blueeyes"
human.head = newhead

To declare an attribute in protocol, you can:

protocol SomeProtocol {    var mustBeSettable: Int { get set }    var doesNotNeedToBeSettable: Int { get }}

In fact, this is also similar to C #. The previous oc does not support attributes in protocol, just a list of methods.

WillSet and didSet are two very interesting things. You can perform operations before and after assigning values to attributes:

class StepCounter {    var totalSteps: Int = 0 {    willSet(newTotalSteps) {        println("About to set totalSteps to \(newTotalSteps)")    }    didSet {        if totalSteps > oldValue  {            println("Added \(totalSteps - oldValue) steps")        }    }    }}let stepCounter = StepCounter()stepCounter.totalSteps = 200// About to set totalSteps to 200// Added 200 stepsstepCounter.totalSteps = 360// About to set totalSteps to 360// Added 160 stepsstepCounter.totalSteps = 896// About to set totalSteps to 896// Added 536 steps

This method adds great flexibility for writing a client app. Encapsulating willSet and didSet into the class helps us to control the attributes of objects more conveniently.

Iii. mutating

This keyword, at least for the first time, is written before func so that func can modify the values of members in struct and protocol extension. If this keyword is not added, the member value is protected and cannot be modified.

For example:

struct Point {    var x = 0.0, y = 0.0    mutating func moveByX(deltaX: Double, y deltaY: Double) {        x += deltaX        y += deltaY    }}var somePoint = Point(x: 1.0, y: 1.0)somePoint.moveByX(2.0, y: 3.0)println("The point is now at (\(somePoint.x), \(somePoint.y))")

This makes the members more secure, because there is no private concept in swift.

Iv. class var

In swift, you can use the static keyword to mark static variables for enum and struct. However, for class members, only one read-only value can be returned in class var mode. As follows:

 

struct SomeStructure {    static var storedTypeProperty = "Some value."    static var computedTypeProperty: Int {    // return an Int value here    }}enum SomeEnumeration {    static var storedTypeProperty = "Some value."    static var computedTypeProperty: Int {    // return an Int value here    }}class SomeClass {    class var computedTypeProperty: Int {    // return an Int value here    }}

In this way, the functions of struct and class are well differentiated. Unlike C #, it can be used at will, but it actually weakens the boundary compared with oc, if you want to create a non-read-only static variable in the class, you can work with struct.

To implement the singleton mode of secure threads, you can combine it with struct:

Source: http://blog.csdn.net/u010124617/article/details/28856711

class SwiftSingleton{    class func shareInstance()->SwiftSingleton{        struct YRSingleton{            static var predicate:dispatch_once_t = 0            static var instance:SwiftSingleton? = nil        }        dispatch_once(&YRSingleton.predicate,{                YRSingleton.instance=SwiftSingleton()            }        )        return YRSingleton.instance!    }}

V. subscript syntax

The so-called subscript is indexed using []. This syntax is very flexible and may be based on some Python styles.

For example, struct, array, and dictionary can all be indexed using subscript:

struct Duden {    let offset:Int    var textCount:Int    subscript(index:Int) -> Int{        get{            return index - offset        }        set(newvalue){            textCount = newvalue * 3        }    }}var duden = Duden(offset:2,textCount:0)duden[9]  //7
duden[9] = 8 //duden.textCount 24

 

6. convenience

Convenience is used for convenient initialization. To put it bluntly, it is equivalent to a constructor overload. For a class, the default or specified initialization method is used as the so-called Designated initialization, if you need to call the Designated initialization to reload the initialization, initialize it as convenience and add the convenience keyword before the method.

class Figure{    var name:String!    var nikname:String?    init(){        name = "John"    }    convenience init(name:String!,nikname:String!){        self.init()        self.name = name        self.nikname = nikname    }}

There are still a lot of extensions involved in inheritance, which will not be listed here.

 

Http://www.wenjuan.com/s/77N7Jj

In short, these new keywords and new features make the new language flexible and secure. Although it will bring you a lot of confusion and inconvenience at the beginning, you will soon fall in love with this language.

Welcome to qingjianfei blood blog: http://www.cnblogs.com/jacklandrin/p/3782831.html

 

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.