我要通过此语句在UserDefaults中访问用户数组中的“全名”
Optional({ message = Hello; success = true; user = { fullname = "xyz"; id = 0; }; })
if currentUser?[""] != nil {
// do something
}
答案 0 :(得分:0)
让我们假设可选的Optional({ message = Hello; success = true; user = { fullname = “xyz”; id = 0; }; })
设置为currentUser
:
if let currentUser = currentUser { //get a not optional value of currentUser
let fullname = currentUser["fullname"] //you will get an optional here
if fullname != nil {
print("Full name: \(fullname!)")
} else {
print("Full name wasn't provided")
}
}
但可以在一行检查中提供相同的内容:
if let currentUser = currentUser, let fullname = currentUser["fullname"] {
print("Full name: \(fullname)"
}
有关您可以在文档https://developer.apple.com/documentation/swift/optional或某些博客文章中阅读的可选内容的更多信息,我建议您使用以下内容:https://hackernoon.com/swift-optionals-explained-simply-e109a4297298
答案 1 :(得分:0)
快捷键3
商店
UserDefaults.standard.set(true, forKey: "Key") //Bool
UserDefaults.standard.set(1, forKey: "Key") //Integer
UserDefaults.standard.set("TEST", forKey: "Key") //setObject
检索
UserDefaults.standard.bool(forKey: "Key")
UserDefaults.standard.integer(forKey: "Key")
UserDefaults.standard.string(forKey: "Key")
检索对象
var returnValue: [datatype]? = UserDefaults.standard.object(forKey: "key_name") as? [datatype]
删除
UserDefaults.standard.removeObject(forKey: "Key")
删除所有键
if let appDomain = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: appDomain)
}