Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Convenience Initializer in Swift with Example

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 494
    Comment on it

    Convenience Initializer used in swift as a supporting initializer. By using the convenience initializer you can put multiple -init along with other and use whichever you want to use.

     

    convenience initializers have the convenience keyword before the -init method. There is no need to have convenience initializers compulsory defined when the class does not require initializers.

     

    A convenience initializer must call another initializer from the same class. It is considered as a supporting initializer for a class. we can understand it by using the following example -

     

    Suppose we have an extension class of UIColor and here we will use the -init methods by using convenience keyword-

    extension UIColor {
    
         convenience init(red: Int, green: Int, blue: Int) {
            assert(red >= 0 && red <= 255, "Invalid red component")
            assert(green >= 0 && green <= 255, "Invalid green component")
            assert(blue >= 0 && blue <= 255, "Invalid blue component")
            
            self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
        }
        
          convenience init(hexString:String) {
    
            let hexString:NSString =  hexString.trimmingCharacters(in: CharacterSet.whitespaces) as NSString
            let scanner            = Scanner(string: hexString as String)
            
            if (hexString.hasPrefix("#")) {
                scanner.scanLocation = 1
            }
            
            var color:UInt32 = 0
            scanner.scanHexInt32(&color)
            
            let mask = 0x000000FF
            let r = Int(color >> 16) & mask
            let g = Int(color >> 8) & mask
            let b = Int(color) & mask
            
            let red   = CGFloat(r) / 255.0
            let green = CGFloat(g) / 255.0
            let blue  = CGFloat(b) / 255.0
            
            self.init(red:red, green:green, blue:blue, alpha:1)
        }
    }

    The above example defines the use of convenience initializer.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: