作者:fst123 | 来源:互联网 | 2023-05-27 12:04
我正在使用一个元组来存储这样的东西.
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'
我该如何解决这个问题?如果它不可能,那么欢迎任何其他保存元组的建议.
谢谢.
1> JoePasq..:
我遇到了类似的场景,试图用一个元组编码NSCoder
.我解决它的方法是手动将元组转换为a Dictionary
.这不是一个很好的解决方案,因为如果元组发生变化,需要在几个地方更改密钥.
我的元组中有一个嵌套的枚举,并给它一个基本类型(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)