What is Extension in Swift 3.0.

Swift provide extension keyword to define the extension. Adding new functionality to the parents class without the modification of the parents class code. We can't override the exiting functionality.  




This tutorial only define the extension on UIView.

Define extension on UIView.
extension UIView{
    func cornerRadiusBorder(){
        self.layer.cornerRadius = 30.0;
        self.layer.borderWidth = 5.0;
        self.layer.borderColor = UIColor.red.cgColor
    }
}

Use extension for UIView.
let viewSub = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width/2.0, height: self.view.frame.height/4.0))
viewSub.center = self.view.center
viewSub.backgroundColor = UIColor.purple
viewSub.cornerRadiusBorder()
self.view.addSubview(viewSub)

Full Code:
import UIKit

extension UIView{
    func cornerRadiusBorder(){
        self.layer.cornerRadius = 30.0;
        self.layer.borderWidth = 5.0;
        self.layer.borderColor = UIColor.red.cgColor
    }
}

class ViewController: UIViewController {
    override func viewDidLoad() {

        let viewSub = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width/2.0, height: self.view.frame.height/4.0))
        viewSub.center = self.view.center
        viewSub.backgroundColor = UIColor.purple
        viewSub.cornerRadiusBorder()
        self.view.addSubview(viewSub)
        super.viewDidLoad()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Output.




Thanks.

What is Extension in Swift 3.0. What is Extension in Swift 3.0. Reviewed by KIRIT MODI on 05:56:00 Rating: 5

No comments:

Powered by Blogger.