Useful Extensions in Swift — Part I

Satheesh Kannan
Sep 2, 2018 · 1 min read

Nowadays, Swift is getting improved very fast. We can see that in each versions of Swift. But we need something extra in sometimes. So I’m sharing my own Swift extensions in these series.

Starting with UIColor:

This extension allows you to use the HEXCode for the UIColor directly as string.

extension UIColor {     class func colorFromHEXString(_ hex:String) -> UIColor {          var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()          if (cString.hasPrefix("#")) {               cString.remove(at: cString.startIndex)          }          if cString.count != 6 {               return UIColor.gray          }          var rgbValue:UInt32 = 0          Scanner(string: cString).scanHexInt32(&rgbValue)          return UIColor(               red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,               green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,               blue: CGFloat(rgbValue & 0x0000FF) / 255.0,               alpha: CGFloat(1.0))     }}

Also with UIView:

This extension allows you to create a copy of view by code. Also these IBInspectable variables allows you to set corner radius, border width & border colour right from your Xib/Storyboards.

extension UIView {     func copyView<T: UIView>() -> T {          return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as! T     }     @IBInspectable var cornerRadius: CGFloat {          get { return layer.cornerRadius }          set {               layer.cornerRadius = newValue               layer.masksToBounds = newValue > 0          }
}
@IBInspectable var borderWidth: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { return UIColor(cgColor: layer.borderColor!) } set { layer.borderColor = newValue?.cgColor } }}

Next.. Part — II will give you few more class extensions.

You can also share your own extensions in comments section.

Thanks..

Satheesh Kannan

Written by

Exploring the World of iOS using Objective C & Swift

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade