将 AnyObject 转换为 [MyEnum: String] 字典
Cast AnyObject as [MyEnum: String] dictionary
我有一个枚举定义为:
enum AlertInterfaceControllerKey {
case Title
case Content
}
我想在呈现 WKInterfaceController
时将其用作上下文,例如:
let alertData = [AlertInterfaceControllerKey.Title: "Title",
AlertInterfaceControllerKey.Content: "Content"]
presentControllerWithName("AlertInterfaceController", context: alertData)
并且,在 AlertInterfaceController
中:
override func awakeWithContext(context: AnyObject?) {
if let alertData = context as? [AlertInterfaceControllerKey: String] {
let title = data[AlertInterfaceControllerKey.Title]
let content = data[AlertInterfaceControllerKey.Content]
// ...
}
}
这里的错误是(在if let
行):
Type '[AlertInterfaceControllerKey : String]' does not conform to protocol 'AnyObject'
非常感谢任何帮助 - 或者更好的方法来处理这个问题。
Swift 不幸的是,枚举值不是 NSObjects,因此您不能将它们用作 NSDictionaries 中的键。它们可以是 Swift 词典中的键,但它们不会转换为 NSDictionary,因此会出现错误。
您可以为枚举指定类型并存储原始值:
enum AlertInterfaceControllerKey: String {
case Title = "TitleKey"
case Content = "ContentKey"
}
let alertData: AnyObject = [AlertInterfaceControllerKey.Title.rawValue: "Title"]
不那么优雅,但可以让您弥合 API 中 Swift 和 Objective-C 类型之间的差距。这个解决方案实际上只是定义一些字符串常量的一种更好的方法。
我有一个枚举定义为:
enum AlertInterfaceControllerKey {
case Title
case Content
}
我想在呈现 WKInterfaceController
时将其用作上下文,例如:
let alertData = [AlertInterfaceControllerKey.Title: "Title",
AlertInterfaceControllerKey.Content: "Content"]
presentControllerWithName("AlertInterfaceController", context: alertData)
并且,在 AlertInterfaceController
中:
override func awakeWithContext(context: AnyObject?) {
if let alertData = context as? [AlertInterfaceControllerKey: String] {
let title = data[AlertInterfaceControllerKey.Title]
let content = data[AlertInterfaceControllerKey.Content]
// ...
}
}
这里的错误是(在if let
行):
Type '[AlertInterfaceControllerKey : String]' does not conform to protocol 'AnyObject'
非常感谢任何帮助 - 或者更好的方法来处理这个问题。
Swift 不幸的是,枚举值不是 NSObjects,因此您不能将它们用作 NSDictionaries 中的键。它们可以是 Swift 词典中的键,但它们不会转换为 NSDictionary,因此会出现错误。
您可以为枚举指定类型并存储原始值:
enum AlertInterfaceControllerKey: String {
case Title = "TitleKey"
case Content = "ContentKey"
}
let alertData: AnyObject = [AlertInterfaceControllerKey.Title.rawValue: "Title"]
不那么优雅,但可以让您弥合 API 中 Swift 和 Objective-C 类型之间的差距。这个解决方案实际上只是定义一些字符串常量的一种更好的方法。