问问题
3289 次
3 回答
3
这是不正确的:
public typealias RESTPostDictionary = [RESTPostDictionaryKey : AnyObject]
你的意思是这样的:
public typealias RESTPostDictionary = [String : AnyObject]
枚举不是字符串。但它是您打算用作键的字符串。
当您使用枚举大小写作为键时,取它的rawValue
:
postDictionary[RESTRequestDictionaryKey.Requests.rawValue] = requestDictionaries
因此,例如,这是合法的:
enum Keys : String {
case Key1 = "hey"
case Key2 = "ho"
case Key3 = "hey nonny no"
}
var d = [String:AnyObject]()
d[Keys.Key1.rawValue] = 1
d[Keys.Key2.rawValue] = 2
于 2015-11-05T16:48:51.927 回答
1
class Box<T> {
let value: T
init(value: T) {
self.value = value
}
}
NSNotificationCenter.defaultCenter().postNotificationName("foo", object: Box(value: YourOwnStruct())) // OK
如果以该类型实现 AnyObjectConvertible,则可以转换 struct/enum 目录。
extension YourOwnStruct: AnyObjectConvertible {}
NSNotificationCenter.defaultCenter().postNotificationName("foo", object: YourOwnStruct()) // OK let value = notification.object as? YourOwnStruct
从这里查看完整的答案/下载源
于 2016-11-29T15:21:58.010 回答
0
为什么不简单地使用枚举作为键?
import Foundation
enum E:String, CustomStringConvertible {
var description: String { return self.rawValue }
case A = "text A"
case B = "B text"
case C = "neither A nor B but C"
}
var dict: Dictionary<E, Any> = [:]
dict[E.A] = "alfa"
dict[E.B] = 1
dict[E.C] = NSDate()
dump(dict)
/*
▿ 3 key/value pairs
▿ [0]: (2 elements)
- .0: E.C
- .1: Nov 8, 2015, 11:01 AM
▿ [1]: (2 elements)
- .0: E.A
- .1: alfa
▿ [2]: (2 elements)
- .0: E.B
- .1: 1
*/
print(dict)
// [neither A nor B but C: 2015-11-08 10:02:47 +0000, text A: "alfa", B text: 1]
可以转换为 JSON 的对象必须具有以下属性:
顶级对象是 NSArray 或 NSDictionary。
所有对象都是 NSString、NSNumber、NSArray、NSDictionary 或 NSNull 的实例。
所有字典键都是 NSString 的实例。
数字不是 NaN 或无穷大。
import Foundation
enum E:String, CustomStringConvertible {
var description: String { return self.rawValue }
case A = "key A"
case B = "key B"
case C = "key C"
}
var dict: Dictionary<NSString, AnyObject> = [:]
dict[E.A.description] = "alfa"
dict[E.B.description] = [1,2,3]
dict[E.C.description] = NSDate()
dict is AnyObject // false
let nsdict = dict as NSDictionary
nsdict is AnyObject // true
print(nsdict)
/*
{
"key A" = alfa;
"key B" = (
1,
2,
3
);
"key C" = "2015-11-09 23:13:31 +0000";
}
*/
于 2015-11-08T10:05:08.407 回答