swiftdefault-valueswift4.1

Struct is fileprivate and cannot be referenced from a default argument value in swift 4.1


Im using a struct with default values like this.

 fileprivate struct Defaults {

    static var BackgroundColor = UIColor.white
    static var TextColor = UIColor.black
    static var Title = "Default Title"
    static var Message = "Default message!"
    static var AnimationDuration: Double = 0.25
    static var Duration: Double = 2
    static var Height: CGFloat = 90
    static var TitleFont: UIFont = UIFont(name: "SourceSansPro-Semibold", size: Defaults.FontSize)!
    static var MessageFont: UIFont = UIFont(name: "SourceSansPro-Regular", size: Defaults.FontSize)!
    static var FontSize: CGFloat = 14 {
        didSet {
            TitleFont = TitleFont.withSize(FontSize)
            MessageFont = MessageFont.withSize(FontSize)
        }
    }
}

I have a method in which passing the these struct values as a default arguments. But in swift4 it's not working.

 class func showWithAnimation(_ animationType: AnimationType = .basic(timingFunction: CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)),
                             title: String = Defaults.Title,
                             message: String = Defaults.Message,
                             backgroundColor: UIColor = Defaults.BackgroundColor,
                             textColor: UIColor = Defaults.TextColor,
                             duration: Double = Defaults.Duration) {

}

Please check the total code here.

What's the work around for this ?

Thankyou...


Solution

  • There are two fixes as stated below,

    1) Take Defaults struct out of DropdownAlert and make it public even properties also as you want to pass them in method signature as below,

    public struct Defaults {
        public static var BackgroundColor = UIColor.white
        public static var TextColor = UIColor.black
        public static var Title = "Default Title"
    }
    
    class func showWithAnimation(_ animationType: AnimationType = .basic(timingFunction: CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)),
                                         title: String = Defaults.Title,
                                         message: String = Defaults.Message) {
        }
    

    2) Keep Defaults inside DropdownAlert but make it public including properties also. And access as below,

    class func showWithAnimation(_ animationType: AnimationType = .basic(timingFunction: CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)),
                                     title: String = DropdownAlert.Defaults.Title,
                                     message: String = DropdownAlert.Defaults.Message) {
    }