[Swift] 建立一個對象

來源:互聯網
上載者:User

標籤:

建立一個對象

先寫一個People類

////  People.swift//  Class////  Created by YouXianMing on 15/3/18.//  Copyright (c) 2015年 YouXianMing. All rights reserved.//import Foundationclass People {        // 變數值    var name : String    var age  : Int        // 初始化方法    init() {        name = "YouXianMing"        age  = 10    }    // 類方法    class func maxAge() -> Int {        return 100    }    class func minAge() -> Int {        return 0    }            // 普通方法    func info(name : String, age : Int) -> String {        return "age:\(age) + name:\(name)"    }        func subInfo() -> String {        return "age:\(age) + name:\(name)"    }}

再寫一個Student類繼承至People類

////  Student.swift//  Class////  Created by YouXianMing on 15/3/18.//  Copyright (c) 2015年 YouXianMing. All rights reserved.//import Foundationclass Student: People {        var score : Float    override init() {        score = 100.0                super.init()    }    }

然後是控制器源碼:

////  ViewController.swift//  Class////  Created by YouXianMing on 15/3/18.//  Copyright (c) 2015年 YouXianMing. All rights reserved.//import UIKitclass ViewController: UIViewController {    // 初始設定變數    var people   : People    var studuent : Student = Student()            // 必要的初始化    required init(coder aDecoder: NSCoder) {        // 調用初始化方法        people      = People()        people.name = "Y.X.M."        people.age  = 20                super.init(coder: aDecoder)    }                        override func viewDidLoad() {        super.viewDidLoad()                        println(people.info("YouXianMing", age: 28))        println(people.subInfo())        println(People.maxAge())    }}

一些需要注意的地方:

 

[Swift] 建立一個對象

相關文章

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.