Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift [1,2] conforms to AnyObject but [Enum.a, Enum.b] does not

Tags:

types

enums

swift

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?

like image 947
Andrew Duncan Avatar asked Apr 21 '15 17:04

Andrew Duncan


People also ask

What does enum do in Swift?

Enumerations (or enums for short) in Swift define a common type for a group of related values. According to the Swift documentation, enums enable you to work with those values in a type-safe way within your code. Enums come in particularly handy when you have a lot of different options you want to encode.

Can enum inherit Swift?

In Swift language, we have Structs, Enum and Classes. Struct and Enum are passed by copy but Classes are passed by reference. Only Classes support inheritance, Enum and Struct don't.

What is raw value in enum Swift?

Raw values are for when every case in the enumeration is represented by a compile-time-set value. The are akin to constants, i.e. So, A has a fixed raw value of 0 , B of 1 etc set at compile time. They all have to be the same type (the type of the raw value is for the whole enum, not each individual case).

What is rawvalue Swift?

A Swift enum can either have raw values or associated values. Why is that? It's because of the definition of a raw value: A raw value is something that uniquely identifies a value of a particular type. “Uniquely” means that you don't lose any information by using the raw value instead of the original value.


1 Answers

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.

like image 178
vacawama Avatar answered Oct 28 '22 06:10

vacawama