https://github.com/YouXianMing

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

一些需要注意的地方:

 

posted @ 2015-03-18 23:26  YouXianMing  阅读(3095)  评论(0编辑  收藏  举报