DCMaxxx
DCMaxxx

Reputation: 2574

Cast AnyObject as [MyEnum: String] dictionary

I have an enum defined as :

enum AlertInterfaceControllerKey {
    case Title
    case Content
}

I would like to use it as a context when presenting a WKInterfaceController, such as :

let alertData = [AlertInterfaceControllerKey.Title: "Title",
                 AlertInterfaceControllerKey.Content: "Content"]
presentControllerWithName("AlertInterfaceController", context: alertData)

And, in AlertInterfaceController:

override func awakeWithContext(context: AnyObject?) {
    if let alertData = context as? [AlertInterfaceControllerKey: String] {
        let title = data[AlertInterfaceControllerKey.Title]
        let content = data[AlertInterfaceControllerKey.Content]
        // ...
    }
}

The error here is (on the if let line) :

 Type '[AlertInterfaceControllerKey : String]' does not conform to protocol 'AnyObject'

Any help - or even better ways to handle this - are much appreciated.

Upvotes: 0

Views: 144

Answers (1)

gregheo
gregheo

Reputation: 4270

Swift enum values are not NSObjects unfortunately, so you can't use them as keys in NSDictionaries. They can be keys in Swift dictionaries, but then they won't cast over to NSDictionary, thus the error.

You could give the enum a type and store the raw values instead:

enum AlertInterfaceControllerKey: String {
  case Title = "TitleKey"
  case Content = "ContentKey"
}

let alertData: AnyObject = [AlertInterfaceControllerKey.Title.rawValue: "Title"]

Not as elegant, but will let you bridge the gap between Swift and Objective-C types in the API. This solution is really just a nicer way of defining some string constants.

Upvotes: 1

Related Questions