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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值