Swift基本概念(三)

Swift##Classes
* The way we declare classes in Swift is also different.

– Swift Does not use header / source separation

– Swift classes are made up in the one .swift file
* Swift allows classes and structures to be developed in the one file and these are then available to the rest of the project.
* Functions can be called from another class by using the following syntax:

– myClass().myFunction()
* You can also make a class function by putting class before func:

– class func myFunction(myInt: int)

– myClass.myFunction(10)

Example

struct myStruct{         
    //…
}

class furniture{        //An example of a class with an initialiser  
    var i = 0;
    init(myInt: int){   //if you have any class variables which is optional, you should have a constructor
        self.i = myInt
    }
}

class table : furniture{       //An example of inheritance
    //…
}

Example

class Person
{
    var name: String
    var age: Int

    init() {
        name = "Undefined"
        age = 1
    }

    init(name:String, age:Int) {
        self.name = name
        self.age = age
    }

    func info() -> String {
        return "\(name) is \(age) years old."
    }
}

Classes - Initializer

  • Initializers in Swift are similar to constructors from Java

    – With some quirks

  • All classes must include a designated initializer

    – This is an initializer that takes in & initializes ALL variables
    – You can have more than one (Typically only 1 is needed)

  • Classes can also include convenience initializers

    – These are initializers that can take a smaller set of parameters and use defaults

    – You MUST call a designated initializer from within this function

Example

class Person: NSObject {
    var m_sName : String?
    var m_nAge: Int?

    init(name: String?, age: Int?){
        self.m_sName = name
        self.m_nAge = age
    }

    convenience init(name:String?){
        self.init(name: name, age:0)
    }

}

Structures

  • Structures are an alternative building block for building your application
    *Key differences compared to Classes:

    – Implicit constructor (init func)

    – Allocated on the stack whereas Classes are allocated on heap

  • This can mean much faster processing

    – Structs are passed by value and not reference (Class)

  • Safer when being used by multiple threads or classes, less chance of memory leaks, etc.

    – Unable to use Inheritance

Example

struct Point {
var x: Int = 0
var y: Int = 0
}

你可能感兴趣的:(Swift)