swift 類方法(+), 實例方法(-),convenience(便利構造函數)


跟OC一樣,swift方法也分為實例方法(-)與類方法(+),然后說下在swift中實例方法,類方法以及便利構造函數的實現

1.實例方法

就是只能用對象實例調用的方法,也可以稱為“對象方法”,與函數語法一樣

class Dog {

    func run() {

        print("run")

    }

}

var d = Dog()

//對象名調用

d.run()

 

 

2.類方法

直接用類調用類型方法,不能用對象調用類型方法,相比swift中的實例方法,用class修飾

class Dog {

   class func run() {

        print("run")

    }

}

//類名調用

Dog.run()

 

3.convenience(便利構造函數)

convenience:便利,使用convenience修飾的構造函數叫做便利構造函數,用於增加init方法

 

extension UIColor {

    convenience init(hexColor: String) {

        

        // 存儲轉換后的數值

        var red:UInt32 = 0, green:UInt32 = 0, blue:UInt32 = 0

        

        // 分別轉換進行轉換

        Scanner(string: hexColor[0..<2]).scanHexInt32(&red)

        

        Scanner(string: hexColor[2..<4]).scanHexInt32(&green)

        

        Scanner(string: hexColor[4..<6]).scanHexInt32(&blue)

        

        self.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1.0)

    }

    

}










免責聲明!

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



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