Bill L
Bill L

Reputation: 2846

Creating a tuple using an associatedtype

I'm trying to alias a tuple type to use throughout my app. I do the initial aliasing like so:

associatedtype JSONReplacementValue = (key: String, value: AnyObject?)

Seems simple enough. When using this without an associatedtype, everything works fine. However, once I alias them, I get errors in the following two places:

var replacementValues: [JSONReplacementValue] = []
if let key = key {
    replacementValues.append((key: key, value: value))
}

This gives an error on the .append line, telling me Cannot invoke 'append' with an argument list of type '(key: String, value: AnyObject?). I've tried replacing what I append to something like JSONReplacementValue(key: key, value: value) but that gives me an error 'Self.JSONReplacementValue' cannot be constructed because it has no accessible initializers

That's the first error I can't get around. The second happens in this code:

for replacementValue in values {
    json[replacementValue.key] = replacementValue.value
}

(values is an array of JSONReplacementValue, defined as a parameter like so values: [JSONReplacementValue])

This gives me an error when I try to access replacementValue.key: Value of type 'Self.JSONReplacementValue' has no member 'key'. This one I have no idea how to solve it.

Is it possible to make a tuple an associatedtype at all? If so, what am I doing wrong here?

Upvotes: 0

Views: 268

Answers (2)

AKM
AKM

Reputation: 568

If you'd like to create a typealias, you should try the typealias keyword. associatedtype works with protocols.

this code works fine with swift 2.2:

typealias JSONReplacementValue = (key: String, value: Any?)

var replacementValues: [JSONReplacementValue] = []
replacementValues.append((key: "one", value: "value"))
print(replacementValues) // prints: [("one", Optional(value))]

Also bear in mind that AnyObject is for class types while Any for all types.

Another thing is you'd be better off with a Struct instead of a Tuple.

From Apple Docs:

Tuples are useful for temporary groups of related values. They are not suited to the creation of complex data structures. If your data structure is likely to persist beyond a temporary scope, model it as a class or structure, rather than as a tuple. For more information, see Classes and Structures.

Upvotes: 1

Bill L
Bill L

Reputation: 2846

Found the answer for any looking in the future. I had this declared in a protocol definition. The methods were all in the protocol extension. By changing it a typealias and moving it into the extension, everything worked as expected.

Upvotes: 0

Related Questions