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:
我在AppDelegate中,试图传递对WatchKit扩展请求的回复。我不能使用枚举数组作为字典中的值,它的值被类型化为AnyObject。在操场上做实验表明:
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?
当然,我可以通过将我的枚举转换成字符串或数字来解决这个问题,但是为什么这是Swift的类型错误呢?
1 个解决方案
#1
24
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.
AnyObject的存在是为了与Objective-C兼容。您只能将对象放入Objective-C可以解释的[AnyObject]数组中。Swift enums与Objective-C不兼容,所以你必须把它们转换成某种东西。
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 x: AnyObject =[0,1]的工作原理,因为Swift会自动将Int的转换处理成Objective-C可以处理的NSNumber类型。不幸的是,Swift enums没有这种自动转换,所以您只能做以下事情:
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
.
这假定枚举具有Objective-C可以处理的底层类型,如字符串或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.
有关更多信息,请参见使用Cocoa数据类型。
#1
24
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.
AnyObject的存在是为了与Objective-C兼容。您只能将对象放入Objective-C可以解释的[AnyObject]数组中。Swift enums与Objective-C不兼容,所以你必须把它们转换成某种东西。
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 x: AnyObject =[0,1]的工作原理,因为Swift会自动将Int的转换处理成Objective-C可以处理的NSNumber类型。不幸的是,Swift enums没有这种自动转换,所以您只能做以下事情:
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
.
这假定枚举具有Objective-C可以处理的底层类型,如字符串或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.
有关更多信息,请参见使用Cocoa数据类型。