UserDefaults通过key-value的一种持久化方案,以键值对的形式存储基本类型数据,类似与安卓的SharePreferences。
使用方式,首先就是要获取standerd
let userDefault=UserDefaults.standard
存取字符串
//存取字符串
var greeting = "Hello, playground"
userDefault.setValue(greeting, forKey: greeting)
print(userDefault.string(forKey: greeting)!)
存取数组
//存取数组
let arrays:[Int]=[1,2,3,4,5,6]
userDefault.setValue(arrays, forKey: "arrays")
print(userDefault.array(forKey: "arrays")!)
存取数字
//存取数字
let number=10086
userDefault.setValue(number, forKey: "number")
print(userDefault.integer(forKey: "number"))
存取布尔类型
//存取布尔类型
let isOpen=false
userDefault.setValue(isOpen, forKey: "isOpen")
print(userDefault.bool(forKey: "isOpen"))
存取小数
//存取小数
let decimal=3.14
userDefault.setValue(decimal, forKey: "decimal")
print(userDefault.double(forKey: "decimal"))
存取字典
//存取字典
let dictionary=["key1":"value1","key2":"value2","key3":"value3","key4":"value4"]
userDefault.set(dictionary, forKey: "dictionary")
print(userDefault.dictionary(forKey: "dictionary")!)