Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm in AppDelegate, trying to pass a reply to a WatchKit Extension Request. I cannot use an array of enums as the value in a Dictionary whose values are typed as AnyObject. Experimenting in a Playground shows this:

enum E : Int {
    case a = 0
    case b
}
var x : AnyObject = [0, 1]  // OK
var y : AnyObject = [E.a, E.b] // [E] is not convertible to AnyObject

Of course I can work around this by converting my enums to strings or numbers, but why is this a type error in Swift?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
545 views
Welcome To Ask or Share your Answers For Others

1 Answer

AnyObject exists for compatibility with Objective-C. You can only put objects into an [AnyObject] array that Objective-C can interpret. Swift enums are not compatible with Objective-C, so you have to convert them to something that is.

var x: AnyObject = [0, 1] works because Swift automatically handles the translation of Int into the type NSNumber which Objective-C can handle. Unfortunately, there is no such automatic conversion for Swift enums, so you are left to do something like:

var y: AnyObject = [E.a.rawValue, E.b.rawValue]

This assumes that your enum has an underlying type that Objective-C can handle, like String or Int.

Another example of something that doesn't work is an optional.

var a: Int? = 17
var b: AnyObject = [a]  // '[Int?]' is not convertible to 'AnyObject'

See Working with Cocoa Data Types for more information.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...