[Swift] 創建一個對象


創建一個對象

先寫一個People類

//
//  People.swift
//  Class
//
//  Created by YouXianMing on 15/3/18.
//  Copyright (c) 2015年 YouXianMing. All rights reserved.
//

import Foundation

class 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 Foundation

class 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 UIKit


class 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())
    }
}

一些需要注意的地方:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM