大家好,那里的每个人都知道如何在 swift 4 中保存数据我制作了一个表情符号应用程序,我可以描述表情符号并且我有一个未来可以在应用程序中保存新的表情符号我在我的表情符号类中编写了这段代码,但正如我想要返回表情符号我收到错误请帮助我。
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
}
}
Run Code Online (Sandbox Code Playgroud)
发生错误是因为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]()
}
Run Code Online (Sandbox Code Playgroud)
并在发生错误时返回一个空数组。或者将返回值声明为可选数组并 return 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]()
}
}
Run Code Online (Sandbox Code Playgroud)