I'm trying to learn Swift and SwiftUI, so I tried to write what I thought would be a simple app, but I’ve quickly run into a problem. I want to be able to select multiple languages and then be able to sort those languages.
I found sample code on the web for both tasks, and I thought I understood how they worked, however they use different data structures and I can’t figure out how to reconcile them. In the code below, preferredLanguages is used to select multiple languages, and sortedLangs is used for sorting. Individually those tasks work fine, but I can’t figure out how to share the results of the multiple selection with the sorting view.
Ideally I’d prefer to have just one class or struct, one var, and one view, but if I can’t do that I need to pass the preferredLanguages data to the sortedLangs var.
Suggestions? Is there some sample code somewhere that does this?
enum LanguageCodes: Int, CaseIterable, Identifiable {
case eng = 0
case ell
case deu
//etc.
var id: LanguageCodes {
self
}
var literal: String {
switch self {
case .eng: return "eng"
case .ell: return "ell"
case .deu: return "deu"
}
}
}
class PreferredLanguages: ObservableObject {
@Published var languages = [LanguageCodes]()
}
struct IdentifiableLanguageItem: Identifiable {
let id = UUID()
let langCode: LanguageCodes
}
@ObservedObject var preferredLanguages = PreferredLanguages()
@State private var sortedLangs: [IdentifiableLanguageItem]