【发布时间】:2016-02-06 14:48:01
【问题描述】:
我有一些类型的字典:
public typealias RESTPostDictionary = [RESTPostDictionaryKey : AnyObject]
public typealias RESTRequestDictionary = [RESTRequestDictionaryKey : AnyObject]
我使用枚举是因为我希望字典的键只是枚举中的一种情况:
public enum RESTPostDictionaryKey : String
{
case Requests = "requests"
}
还有:
public enum RESTRequestDictionaryKey : String
{
case RequestURI = "request_uri"
case HTTPMethod = "http_method"
case DataDictionary = "data_dictionary"
case RequestIdentifier = "request_identifier"
case ResponseFormats = "response_formats"
}
由于我的枚举在技术上是String 类型,我认为编译器获取其底层字符串值(确实符合AnyObject)并使用它是没有问题的。但我收到警告:
Cannot assign value of type ‘Array<RESTRequestDictionary>’ aka … to type 'AnyObject?’
在以下函数中:
class public func postDictionaryWithRequestDictionaries(requestDictionaries: Array<RESTRequestDictionary>) -> RESTPostDictionary
{
var postDictionary = RESTPostDictionary()
postDictionary[.Requests] = requestDictionaries
return postDictionary
}
有没有什么方法可以告诉编译器通过使用协议或其他方式来获取它的String,而不必依赖肮脏且不像 Swift 的 .rawValue?
还是我做错了什么?
【问题讨论】:
-
为什么限制字典只包含对象?如果你不只需要对象,你可以把
AnyObject改成Any -
我不知道
Any,但是当我使用Any时,我不能将字典用作字典,例如我使用方法NSJSONSerialization.dataWithJSONObject(postDictionary, options: [])并得到错误那’RESTPostDictionary’ does not conform to expected type ‘AnyObject’ -
哦是的,在那种情况下你必须使用对象,Obj-C 不能处理其他任何东西