初探swift語言的學習筆記四(類對象,函數)

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   使用   

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 Foundationvar 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.0you set computerPrice value is 2000.0you call computerPrice.設定後的價錢為:2000.0準備將totalPrice值(原值為:0)設為: 100設定後新值比舊值添加?了100準備將totalPrice值(原值為:100)設為: 400設定後新值比舊值添加?了300準備將totalPrice值(原值為:400)設為: 900設定後新值比舊值添加?了500a=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.02.03.0支援USB介面:2.0,3.0,)5.0擴充USB介面:5.0,xp 3default windows xp 3this is destory?

樣子最好自己寫一個從過種中去學習。光看,或許還不清楚是什麼。

謝謝大家,由於是英文文檔,看得我頭也比較痛,有些要猜和執行來理解,還有些沒有完好有點亂。有些沒有搞懂所以就沒有整理好。

大家共同學習,共同進步。


相關文章

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.