JSONUtilities icon indicating copy to clipboard operation
JSONUtilities copied to clipboard

Handle types that are both RawRepresentable and JSONPrimitiveConvertible

Open Jon889 opened this issue 6 years ago • 1 comments

The use case is you can already have an enum that conform to JSONPrimitiveConvertible. But if you need the enum to have a raw type like String, then you get an ambiguous call because it's both RawRepresentable and JSONPrimitiveConvertable. So adding these methods resolves that ambiguity.

eg:

    public enum NotificationType: String, JSONPrimitiveConvertible {
	case info, warning, success, error
	public static func from(jsonValue: String) -> Self? {
		self.init(rawValue: jsonValue.trimmingWhitespace.lowercased())
	}
    }

    let x: NotificationType = properties.json(atKeyPath: "status") ?? .info

Now works with this PR.

Unfortunately function bodies are duplicated exactly from the JSONPrimitiveConvertable functions as I couldn't find a way to reference that exact method unambiguously.

Jon889 avatar Apr 17 '20 12:04 Jon889

@Jon889 could we have some unit tests for these new cases?

lucianomarisi avatar Apr 20 '20 16:04 lucianomarisi