hi every ones there anyone know how to save data in swift 4 i made a emoji app that i can describe the emojis and i have a future that i can save the new emoji in the app i wrote this code in my emoji class but as i want return the emoji i get an error please help me .
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
}
}
The error occurs because decodemoj
is out of scope. You need to write
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]()
}
and return an empty array in case of an error. Alternatively declare the return value as optional array and return nil
.
But why not a do - catch
block?
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]()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With