初探swift语言的学习笔记四(类对象,函数)

作者:fengsh998

原文地址:http://blog.csdn.net/fengsh998/article/details/29606137

转载请注明出处

假设认为文章对你有所帮助,请通过留言或关注微信公众帐号fengsh998来支持我,谢谢!

swift扩展了非常多功能和属性,有些也比較奇P。仅仅有慢慢学习,通过经验慢慢总结了。

以下将初步学习一下类的写法。

码工,最大爱好就是看码,而不是文字,太枯燥。

//
//  computer.swift
//  swiftDemo
//
//  Created by apple on 14-6-8.
//  Copyright (c) 2014年 fengsh. All rights reserved.
/*
    写本样例的目的在于高速学习swift类的写法,包含知识点:
1.属性设置
2.构造、释构
3.接口实现多态
4.函数的重载(重载非常特别不须要overload关键词Delphi的朋友注意了)和重写(override)
5.类函数(静态成员函数)
6.各种函数的声明,带參,默认值,多个返回,多个输出參数,多个未确定參数的函数,内连函数等
7.函数类型变量,函数地址作为传參,返回函数地址(还未完工,学习中)
8.单例
9.swift新功能willset,didset @lazy 属性
10.(兴许学习补充)

*/

import Foundation

var instance : Computer?
let unk = "unKnow"

//显示器屏幕宽高
struct MonitorWH {
    var width           = 0
    var height          = 0
    var resolution      = 0.0           //分辩率
}

//协义,接口,实现多重继承
protocol ProtocolComputer {
    var price : Double {get}            //仅仅有get方法

    func runComputer()
}

//计算机类型
enum ComputerType :Int
{
    case none
    case book                           //笔记本
    case superBook                      //超级笔记本
    case home                           //家庭电脑
}

func callbackWhenStarting()//computer:Computer
{

}

//计算机类
class Computer : NSObject,ProtocolComputer
{
    var cpu         = unk               //cpu
    var memory      = unk               //内存
    var hardDisk    = unk               //硬盘
    var monitor     = unk               //显示器
    var cpName      = unk               //品牌
    var computertype : ComputerType = .none

    //@lazy //这关键词声明的有啥作用啊????

    //继承接口的属性
    var price :Double = 0.0

    //willset didset属性
    var totalPrice: Int = 0 {
        willSet(newTotalPrice) { //參数使用new+变量名且变量名首地址大写
            println("准备将totalPrice值(原值为:\(totalPrice))设为: \(newTotalPrice)")
            //to do somthing before set.
        }
        didSet {
            if totalPrice > oldValue  {
                println("设置后新值比旧值添加?了\(totalPrice - oldValue)")
            }
        }
    }

    //声明一个set,get属性
    var computerPrice: Double {
        get {
            println("you call computerPrice.")
            return price
        }
        set {
            price = newValue
            println("you set computerPrice value is \(price)")
        }
    }

    //默认构造
    init()
    {
        println("default creatrustor is called.")
    }

    //默认构造 不能和init()共存
//    convenience init() {
//        self.init(computerName: "unknow" ,price:0)
//    }

    //自己定义构造函数
    init(computerName:String,price:Double)
    {
        println("custom creatrustor is called.")
        self.cpName = computerName
        self.price = price
    }

    //释构
    deinit {
        println("this is destory?")
    }

    func description() -> String
    {
        //还真不知道怎么换行来写代码曾经能够使用\如今被作參用了
        return "Computer description : product \(self.cpName) ,type is \(self.computertype.toRaw()) , cpu is \(self.cpu) ,memory is \(self.memory),disk is \(self.hardDisk) ,monitor is \(self.monitor) ,price is \(self.price)"
    }

    //类函数 (OC 中的+号操作, c/c++ 中的static 函数)
    class func shareInstance() -> Computer
    {
        return Computer()
    }

    //开机关机 (不带返回值函数)
    func operationComputer(onOrOff : Bool)
    {
        if onOrOff
        {
            println("computer is starting")
        }
        else
        {
            println("computer is stopping")
        }
    }

    //无參,无返回值函数
    func computerRunning()
    {
        println("computer is running")
    }

    //多个返回值(即输出參数)
    func getComputerConfig()->(cpu:String,hd:String,mem:String,mon:String)
    {
        return (self.cpu,self.hardDisk,self.memory,self.monitor)
    }

    //使用inout參数来作为输出參数
    func getComputerConfig(inout cpu:String,inout hd:String,inout mem:String,inout mon:String)
    {
        cpu     = self.cpu
        hd      = self.hardDisk
        mem     = self.memory
        mon     = self.monitor
    }

    //外部參数名函数(目的是让调用者更加清楚每一个參数的详细函义)
    //computerCPU,withComputerhardDisk,withComputerMemory,withComputerMonitor 这些都是外部參数名
    //在调用时必须带上
    func setComputerConfig(computerCPU cpu:String,withComputerhardDisk hd:String,
        withComputerMemory mem:String,withComputerMonitor mon:String)
    {
        self.cpu            = cpu
        self.hardDisk       = hd
        self.memory         = mem
        self.monitor        = mon
    }

    //使用#来把变量名提升了具有外部參数名作用的变量名,这样就不用再写一次外部參数名(在外部參数名与变量名同样时使用)
    func setComputerConfig(#cpu:String,disk:String,mem:String,mon:String)
    {
        self.cpu            = cpu
        self.hardDisk       = disk
        self.memory         = mem
        self.monitor        = mon
    }

    //參数的默认值
    func macBookPro(pname:String = "Apple",cpu:String = "Intel Core I5",type:ComputerType,
        mem:String = "2G",disk:String ,mon:String = "Intel HD Graphics 4000")
    {
        self.cpu            = cpu
        self.hardDisk       = disk
        self.memory         = mem
        self.monitor        = mon
        self.cpName         = pname
        self.computertype   = type
    }

    //可变參数
    func usbNumbers(usbs:String...) -> String
    {
        var ret : String = ""
        for usb in usbs
        {
            println(usb)
            ret += (usb + ",")
        }
        return ret
    }

    //常量參数、变量參数
    //虽然函数内部改动了version 但并不影响原来外部设定的值
    func lookWindowsVersion(var version:String) ->String
    {
        version = "default windows " + version
        return version
    }

    //mutating func

    func getResolution(pname:String) -> MonitorWH
    {
        var mt = MonitorWH(width: 1364,height: 1280,resolution: 16/9)
        if pname == "Phripse"
        {
            mt = MonitorWH(width: 5555,height: 3333,resolution: 29/10)
        }

        return mt
    }

    //函数作为參数传參

    //var callbackWhenStarting : ()->() = callbackWhenStarting
    //函数作为返回值
    //函数作为变量定义
    //嵌套函数
    func openTask()
    {
        func openOtherTask()
        {
            println("open other task")
        }
        println("open task")
    }

    //函数重写
    func lookComputerBasicHardInfo(computer:Computer)
    {

    }

    //接口实现
    func runComputer()
    {
        println("Computer run.")
    }
}

class Lenove : Computer
{
    override func lookComputerBasicHardInfo(computer:Computer)
    {
        if computer is Lenove  //is as 操作。
        {
            println("这是联想")
        }
    }
}

调用DEMO:

 //var cpt = Computer()   //调用默认构造
        var cpt = Computer(computerName: "Apple",price:12000)   //调用自己定义构造
        println(cpt.description)
        println(cpt.getComputerConfig())

        //属性測试
        println("价钱为:\(cpt.computerPrice)")
        cpt.computerPrice = 2000.0;
        println("设置后的价钱为:\(cpt.computerPrice)")

        //測试willset didset
        cpt.totalPrice = 100;
        cpt.totalPrice = 400;
        cpt.totalPrice = 900;

        var a = "",b = "",c = "",d = ""
        cpt.getComputerConfig(&a,hd: &b,mem: &c,mon: &d)
        println("a=\(a),b=\(b),c=\(c),d=\(d)")

        cpt.setComputerConfig(computerCPU :"inter i5", withComputerhardDisk:"WD 500",
            withComputerMemory:"4G",withComputerMonitor:"Phripse")

        println("最新配置:\(cpt.description)")

        cpt.setComputerConfig(cpu: "AMD", disk: "HD 1T", mem: "8G", mon: "SamSung")
        println("最新配置:\(cpt.description)")

        //使用缺省值调用函数
        cpt.macBookPro(type: ComputerType.book,disk: "5")
        println("平果配置:\(cpt.description)")

        let usbSupportType = cpt.usbNumbers("2.0","3.0")
        println("支持USB接口:\(usbSupportType))")

        let extentUsbType = cpt.usbNumbers("5.0")
        println("扩展USB接口:\(extentUsbType)")

        var version = "xp 3";
        let newversion = cpt.lookWindowsVersion(version);
        println(version)
        println(newversion)

输出:

custom creatrustor is called.
Computer description : product Apple ,type is 0 , cpu is unKnow ,memory is unKnow,disk is unKnow ,monitor is unKnow ,price is 12000.0
(unKnow, unKnow, unKnow, unKnow)
you call computerPrice.
价钱为:12000.0
you set computerPrice value is 2000.0
you call computerPrice.
设置后的价钱为:2000.0
准备将totalPrice值(原值为:0)设为: 100
设置后新值比旧值添加?了100
准备将totalPrice值(原值为:100)设为: 400
设置后新值比旧值添加?了300
准备将totalPrice值(原值为:400)设为: 900
设置后新值比旧值添加?了500
a=unKnow,b=unKnow,c=unKnow,d=unKnow
最新配置:Computer description : product Apple ,type is 0 , cpu is inter i5 ,memory is 4G,disk is WD 500 ,monitor is Phripse ,price is 2000.0
最新配置:Computer description : product Apple ,type is 0 , cpu is AMD ,memory is 8G,disk is HD 1T ,monitor is SamSung ,price is 2000.0
平果配置:Computer description : product Apple ,type is 1 , cpu is Intel Core I5 ,memory is 2G,disk is 5 ,monitor is Intel HD Graphics 4000 ,price is 2000.0
2.0
3.0
支持USB接口:2.0,3.0,)
5.0
扩展USB接口:5.0,
xp 3
default windows xp 3
this is destory?

样子最好自己写一个从过种中去学习。光看,或许还不清楚是什么。

谢谢大家,由于是英文文档,看得我头也比較痛,有些要猜和执行来理解,还有些没有完好有点乱。有些没有搞懂所以就没有整理好。

大家共同学习,共同进步。

初探swift语言的学习笔记四(类对象,函数)

时间: 2024-07-29 23:57:27

初探swift语言的学习笔记四(类对象,函数)的相关文章

初探swift语言的学习笔记四-2(对上一节有些遗留进行处理)

在上一节中有些问题还没有弄清,在这里自己写了一下,做了一下验证,并希望能给读者有所帮助. 看例子: 例子中包括 callback函数的声明与使用 函数作为形参进行传递 函数作为返回值 函数支持泛型,当然class也支持. import Foundation typealias Point = (Int, Int) let origin: Point = (0, 0) //初始化函数用 func willDoit(sender : CallBackManager) { println("willD

初探swift语言的学习笔记(类对象,函数)

swift扩展了很多功能和属性,有些也比较奇P.只有慢慢学习,通过经验慢慢总结了. 下面将初步学习一下类的写法. 码工,最大爱好就是看码,而不是文字,太枯燥. // // computer.swift // swiftDemo // // Created by apple on 14-6-8. // Copyright (c) 2014年 fengsh. All rights reserved. /* 写本例子的目的在于快速学习swift类的写法,包括知识点: 1.属性设置 2.构造.释构 3.

初探swift语言的学习笔记十一(performSelector)

作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/35842441 转载请注明出处 如果觉得文章对你有所帮助,请通过留言或关注微信公众帐号fengsh998来支持我,谢谢! 在OC中使用好好的performSelector,但不知为什么在swift有意的被拿掉了.更有甚者连IMP, objc_msgSend也不能用了.虽然想不通为什么,但应该有他的道理.就不纠结了. 大家可能在OC中使用得更多的就是延时处理,及后台处

初探swift语言的学习笔记六(ARC-自动引用计数,内存管理)

Swift使用自动引用计数(ARC)来管理应用程序的内存使用.这表示内存管理已经是Swift的一部分,在大多数情况下,你并不需要考虑内存的管理.当实例并不再被需要时,ARC会自动释放这些实例所使用的内存. 另外需要注意的: 引用计数仅仅作用于类实例上.结构和枚举是值类型,而非引用类型,所以不能被引用存储和传递. swift的ARC工作过程 每当创建一个类的实例,ARC分配一个内存块来存储这个实例的信息,包含了类型信息和实例的属性值信息. 另外当实例不再被使用时,ARC会释放实例所占用的内存,这些

初探swift语言的学习笔记(可选类型?和隐式可选类型!)

可选类型.隐式可选类型 其次swift还引入一个较有趣的初始值设置语法使用"?"操作符及"!"号操作符 如:"var optionalString: String? = "Hello" optionalString == nil var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = op

初探swift语言的学习笔记九(OC与Swift混编)

swift 语言出来后,可能新的项目直接使用swift来开发,但可能在过程中会遇到一些情况,某些已用OC写好的类或封装好的模块,不想再在swift 中再写一次,哪就使用混编.这个在IOS8中是允许的. 先中简单的入手,先研究在同一个工程目录下混合使用的情况. 为了演示.先准备两个类 第一个是swift语言写的类,文件名为 act.swift import Foundation class Act : NSObject { func hasAct(tag:Int) -> String { swit

初探swift语言的学习笔记十(block)

作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/35783341 转载请注明出处 如果觉得文章对你有所帮助,请通过留言或关注微信公众帐号fengsh998来支持我,谢谢! 在前面一些学习中,原本把闭包给理解成了block尽管有很多相似之处,但block还是有他自己的独特之外.近日,在写oc/swift混合编码时,有时候需要swift回调oc,oc回调swift . 因此我把swift中的 block 常见的声明和写

初探swift语言的学习笔记八(保留了许多OC的实现)

尽管swift作为一门新语言,但还保留了许多OC的机制,使得swift和OC更好的融合在一起.如果没有OC基础的先GOOGLE一下. 如:KVO,DELEGATE,NOTIFICATION. 详见DEMO. import Foundation @objc // 需要打开objc标识,否则@optional编译出错 protocol kvoDemoDelegate { func willDoSomething() @optional func didDoSomething() //可选实现, }

初探swift语言的学习笔记七(swift 的关健词)

每一种语言都有相应的关键词,每个关键词都有他独特的作用,来看看swfit中的关键词: 关键词: 用来声明的: “ class, deinit, enum, extension, func, import, init, let, protocol, static, struct, subscript, typealias, var.” 用于子句的: “ break, case, continue, default, do, else, fallthrough, if, in, for, retur