I'm using Swift 4.1 in Xcode 9.4.1. I need to create a dictionary that can hold a finite variety of data types as values, so I wanted to define the dictionary as something more specific than [String: Any]
. I decided to create a protocol, and take advantage of Swift 4's conditional conformance to allow nested dictionaries of the same type. My code looked like this:
protocol MetricsValue {}
typealias MetricsDictionary = [String: MetricsValue]
//Now define which types can go in the dictionary:
extension String: MetricsValue {}
extension Dictionary: MetricsValue where Key == String, Value == MetricsDictionary {}
This fails to compile, with the error: "Type alias MetricsDictionary references itself." I then tried this, not really expecting it to work:
protocol MetricsValue {}
//Now define which types can go in the dictionary:
extension String: FDGoogleMetricsValue {}
extension Dictionary: MetricsValue where Key == String, Value == MetricsDictionary {}
typealias MetricsDictionary = [String: MetricsValue]
And it compiles! Defining the type alias below the extension works. Why does the second example compile, but the first example fail?
Edit: After thinking about it, I actually wanted to make MetricsDictionary
conform to MetricsValue
, i.e. extension Dictionary: MetricsValue where Key == String, Value == MetricsValue
, which works without any problems. I was going to delete the question, but it still seems odd, so I'll keep in case other people find it helpful.