[Swift] 创建一个对象

本文介绍了一个简单的Swift面向对象编程示例,包括定义基类People及其子类Student,并演示了如何在ViewController中创建对象实例及调用其方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建一个对象

先写一个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())
    }
}

一些需要注意的地方:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值