上QQ阅读APP看书,第一时间看更新
Adding new initializer
Extensions allow you to add new initializer to the currently available initializer for any particular type. For example, let's take a look at the CGRect class. CGRect has three initializers: empty init; init with origin and size; and init with x, y, width, and height. We will add new initializer with a center point and a rectangular size. Let's take a look at how to do it:
extension CGRect{ init(center:CGPoint, size:CGSize){ let x = center.x - size.width / 2 let y = center.y - size.height / 2 self.init(x: x, y: y, width: size.width, height: size.height) } } let rect = CGRect(center: CGPoint(x: 50, y: 50), size: CGSizeMake(100, 80)) // {x 0 y 10 w 100 h 80}