AppStorage – Save Array

Archive Arrays
class Storage: NSObject {

static func archiveStringArray(object : [String]) -> Data {
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: object, requiringSecureCoding: false)
return data
} catch {
fatalError("Can't encode data: \(error)")
}

}

static func loadStringArray(data: Data) -> [String] {
do {
guard let array = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [String] else {
return []
}
return array
} catch {
fatalError("loadWStringArray - Can't encode data: \(error)")
}
}
}
@AppStorage(„nameArray", store: UserDefaults(suiteName: "group.de.domain.MyApp“))
var nameArray: Data = Data()

var tempArray = ["David", "Caro", "Adrian"]

//Save Array
nameArray = Storage.archiveStringArray(object: tempArray)
//Retrieve Array Example (SwiftUI)

ForEach(0..<{getStrings(data: entry.nameArray)).count) { i in
Text(getStrings(data: entry.nameArray)[i])

}

func getStrings(data: Data) -> [String] {
return Storage.loadStringArray(data: data)
}
class Storage: NSObject {

static func archiveColorArray(object : [UIColor]) -> Data {
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: object, requiringSecureCoding: false)
return data
} catch {
fatalError("Can't encode data: \(error)")
}

}

static func loadColorArray(data: Data) -> [UIColor] {
do {
guard let array = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [UIColor] else {
return []
}
return array
} catch {
fatalError("loadWStringArray - Can't encode data: \(error)")
}
}
}

Swift (iOS, iPadOS & macOS) Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store