Adam Carter Adam Carter - 3 days ago 6
Swift Question

Make a Swift (2.1) enum conform to AnyObject

I’ve got a few dictionaries that are of types:

public typealias RESTPostDictionary = [RESTPostDictionaryKey : AnyObject]
public typealias RESTRequestDictionary = [RESTRequestDictionaryKey : AnyObject]


I’m using enums because I want the key of the dictionary to only be one of the cases in the enum:

public enum RESTPostDictionaryKey : String
{
case Requests = "requests"
}


And:

public enum RESTRequestDictionaryKey : String
{
case RequestURI = "request_uri"
case HTTPMethod = "http_method"
case DataDictionary = "data_dictionary"
case RequestIdentifier = "request_identifier"
case ResponseFormats = "response_formats"
}


Since my enum is technically a
String
type, I’d have thought this would be no problem for the compiler to get its underlying string value (which does conform to
AnyObject
) and use that. But I get the warning:

Cannot assign value of type ‘Array<RESTRequestDictionary>’ aka … to type 'AnyObject?’


in the following function:

class public func postDictionaryWithRequestDictionaries(requestDictionaries: Array<RESTRequestDictionary>) -> RESTPostDictionary
{
var postDictionary = RESTPostDictionary()

postDictionary[.Requests] = requestDictionaries

return postDictionary
}


Is there any way of telling the compiler to get its
String
through the use of a protocol or something else without having to rely on the dirty and un-Swift-like .rawValue?

Or am I doing something wrong?

Answer

This is not correct:

public typealias RESTPostDictionary = [RESTPostDictionaryKey : AnyObject]

What you mean is this:

public typealias RESTPostDictionary = [String : AnyObject]

The enum is not the string. But it is the string that you intend to use as the key.

When you use the enum case as the key, take its rawValue:

postDictionary[RESTRequestDictionaryKey.Requests.rawValue] = requestDictionaries

Thus, for example, this is legal:

enum Keys : String {
    case Key1 = "hey"
    case Key2 = "ho"
    case Key3 = "hey nonny no"
}

var d = [String:AnyObject]()
d[Keys.Key1.rawValue] = 1
d[Keys.Key2.rawValue] = 2
Comments