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)

    }

    

}