嗨,每个人都知道如何在swift 4中保存数据我制作了一个表情符号应用程序,我可以描述表情符号,并且有一个未来,我可以将新的表情符号保存在我在表情符号类中编写的代码的应用程序中,但是当我想返回表情符号时,我会遇到一个错误,请帮助我。<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<</p>
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]()
}
}