ConfusedByCode
ConfusedByCode

Reputation: 1730

In Swift, why does the error "type alias references itself" depend on where the type alias is defined?

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.

Upvotes: 2

Views: 586

Answers (1)

shio
shio

Reputation: 408

It's quite interesting, the code you have provided:

protocol MetricsValue {}
typealias MetricsDictionary = [String: MetricsValue]

extension String: MetricsValue {}
extension Dictionary: MetricsValue where Key == String, Value == MetricsDictionary {}

fails to compile in Xcode 9.4.1, but it has no problems in Xcode 10.0 beta (10L176w). Also i have compiled the code in online swift compile with Swift 4.1.2 and it also has no problems.

There was same kind of bug report for Xcode 8.2.1 and they fixed it in 8.3. Maybe it presented itself in the current Xcode version.

Upvotes: 1

Related Questions