Search code examples
iosswift3swift-extensions

How to instantiate a Type in a Type extension method?


I am trying to create a Type extension for UIColor per the code snippet below, but I'm receiving a build error. When I try to create the UIColor object in my Type extension method, the UIColor constructor is referencing the encapsulating UIColor extension I created. How to instantiate a UIColor object in my UIColor Type extension method?

 // Error: "Argument to call takes no parameters"  

      import UIKit
        import Foundation

        extension UIColor {

            class UIColor {
                var seventyPercentGreyColor : UIColor {
                    get {
                        let seventyPercent:CGFloat = (1.0 - 0.70)
                        // The below line of code produces a
                        // "Argument to call takes no parameters" build error
                        let color = UIColor(red: seventyPercent, green: seventyPercent, blue: seventyPercent, alpha:1.0)
                        return color
                    }
                }
            }
        }

Solution

  • You can just declare it as static. If you just need grey levels you can use UIColor(white:alpha:) initializer:

    extension UIColor {
        static var seventyPercentBlack: UIColor { return UIColor(white: 0.3, alpha: 1) }
    }
    
    UIColor.seventyPercentBlack   // w 0,3 a 1,0