我正在使用一个元组来存储这样的东西.
var accessLavels: (hasInventoryAccess: Bool,hasPayrolAccess: Bool) accessLavels = (hasInventoryAccess: true,hasPayrolAccess: false)
现在我想将它保存在NSUserDefaults中.
NSUserDefaults.standardUserDefaults().setValue(accessLavels,forKey: "AccessLevelKey") NSUserDefaults.standardUserDefaults().synchronize()
但是我收到以下错误.
类型'(hasInventoryAccess:Bool,hasPayrolAccess:Bool)’不符合协议’AnyObject’
我该如何解决这个问题?如果它不可能,那么欢迎任何其他保存元组的建议.
谢谢.
解决方法
我遇到了一个尝试用NSCoder编码元组的类似场景.我解决它的方法是手动将元组转换为字典.这不是一个很好的解决方案,因为如果元组发生变化,需要在几个地方更改密钥.
我的元组中有一个嵌套的枚举,并给它一个基本类型(String),我从中转换了原始值.这是一个额外的工作,但幸运的是你的只是原始人.
# SerializeableTuple.swift typealias AccessTuple = (hasInventoryAccess: Bool,hasPayrolAccess: Bool) typealias AccessDictionary = [String: Bool] let InventoryKey = "hasInventoryAccess" let PayrollKey = "hasPayrollAccess" func serializeTuple(tuple: AccessTuple) -> AccessDictionary { return [ InventoryKey : tuple.hasInventoryAccess,PayrollKey : tuple.hasPayrolAccess ] } func deserializeDictionary(dictionary: AccessDictionary) -> AccessTuple { return AccessTuple( dictionary[InventoryKey] as Bool!,dictionary[PayrollKey] as Bool! ) }
# Encoding / Decoding var accessLavels: AccessTuple = (hasInventoryAccess: true,hasPayrolAccess: false) // Writing to defaults let accessLevelDictionary = serializeTuple(accessLavels) NSUserDefaults.standardUserDefaults().setObject(accessLevelDictionary,forKey: "AccessLevelKey") // Reading from defaults let accessDic = NSUserDefaults.standardUserDefaults().dictionaryForKey("AccessLevelKey") as AccessDictionary let accessLev = deserializeDictionary(accessDic)