嗨,每个人都知道如何在 swift 4 中保存数据
我制作了一个表情符号应用程序,我可以描述表情符号,我有一个 future ,我可以在应用程序中保存新的表情符号
import Foundation
struct Emoji : Codable {
var symbol : String
var name : String
var description : String
var usage : String
static let documentsdirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
static let archiveurl = documentsdirectory.appendingPathComponent("emojis").appendingPathExtension("plist")
static func SaveToFile (emojis: [Emoji]) {
let propetyencod = PropertyListEncoder()
let encodemoj = try? propetyencod.encode(emojis)
try? encodemoj?.write(to : archiveurl , options : .noFileProtection)
}
static func loadeFromFile () -> [Emoji] {
let propetydicod = PropertyListDecoder()
if let retrivdate = try? Data(contentsOf: archiveurl),
let decodemoj = try?
propetydicod.decode(Array<Emoji>.self, from: retrivdate){
}
return decodemoj in this line i get error
}
}
最佳答案
发生错误的原因是 decodemoj
超出范围。你需要写
static func loadeFromFile() -> [Emoji] {
let propetydicod = PropertyListDecoder()
if let retrivdate = try? Data(contentsOf: archiveurl),
let decodemoj = try? propetydicod.decode(Array<Emoji>.self, from: retrivdate) {
return decodemoj
}
return [Emoji]()
}
并在出现错误时返回一个空数组。或者将返回值声明为可选数组并返回
nil
.但为什么不是
do - catch
堵塞?static func loadeFromFile() -> [Emoji] {
let propetydicod = PropertyListDecoder()
do {
let retrivdate = try Data(contentsOf: archiveurl)
return try propetydicod.decode([Emoji].self, from: retrivdate)
} catch {
print(error)
return [Emoji]()
}
}
关于swift4 - 如何使用可编码和文件管理器在 swift 4 中保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46549793/