How to make enum init method public in a package?

Viewed 29

It is publis, but seems, it is not "enough":

public enum DataToValidate {
    case object(JSONObject)
    case array(JSONArray)
    case string(String)
    case number(Double)
}

extension DataToValidate {
    public init(associatedValue: Any) {
        switch associatedValue {
        case is Int:
            self = .number(Double(associatedValue as! Double))
        case is Float:
            self = .number(Double(associatedValue as! Double))
        case is Double:
            self = .number(associatedValue as! Double)
        case is String:
            self = .string(associatedValue as! String)
        case is JSONObject:
            self = .object(associatedValue as! JSONObject)
        case is JSONArray:
            self = .array(associatedValue as! JSONArray)
        default:
            fatalError("Unrecognized type!")
        }
    }
}

when embedding, I got this:

'DataToValidate' initializer is inaccessible due to 'internal' protection level

Funny, because all the types used by DataToValidate are public.

1 Answers

The code looks fine although it will crash if you pass an Int to the initializer because you're force casting it to double. A better pattern would be

switch associatedValue {
  case let iVal as? Int:
    self = .number(Double(iVal))

  case let fVal as? Float:
    self = .number(Double(fVal))

  // etc...
}
Related