Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Initializers may only be declared within a type

Tags:

ios

swift

Here's my code

extension UIImage {
    convenience init(color: UIColor, size: CGSize = CGSizeMake(1, 1)) {
        let rect = CGRectMake(0, 0, size.width, size.height)
        UIGraphicsBeginImageContext(rect.size)

        let context = UIGraphicsGetCurrentContext()
        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        init(CGImage: image.CGImage!)
    }
}

On init(CGImage: image.CGImage!), I get the error

Initializers may only be declared within a type

like image 281
Sahil Kapoor Avatar asked Dec 17 '15 07:12

Sahil Kapoor


1 Answers

The dedicated initializer is called from the convenience initializer with self.init(...):

self.init(CGImage: image.CGImage!)

Without self. (or super. if you call the superclass initializer) the compiler mistakes init(...) for the declaration of an init method.

like image 105
Martin R Avatar answered Oct 16 '22 11:10

Martin R