I am trying to filter a multi-dimensional array. Below is my swiftUI view.
import SwiftUI
struct Person {
let name: String
let job: String
let age: Int
let rating: Rating
enum Rating: String {
case Poor, Ok, Good, Excellent
}
}
extension Person: CustomStringConvertible {
var description: String {
"Name: \(name), Job: \(job), Age: \(age), Rating: \(rating)"
}
}
struct view: View {
let name = "Paul"
var array2d: [[String]].map(Person.init)
let person = array2d.first(where: {$0.name == name})
var body: some View {
ZStack{
Color.white
Text("\(self.person)")
}
}
}
array2d is passed from the ViewController to the swiftUI view and it looks like this:
var array2d = [[Paul, CEO, 30, Good], [John, Manager, 45, Ok], [Scott, Assistant, 22, Poor], [Robert, CEO, 67, Excellent], [Paul, CEO, 56, Poor], [John, Manager, 23, Good]]
I am getting several errors with the the above code:
on var array2d: [[String]].map(Person.init) the errors:
Consecutive declarations on a line must be separated by ';'
Expected declaration
and on let person = array2d.first(where: {$0.name == name})
Cannot use instance member 'array2d' within property initializer; property initializers run before 'self' is available
Cannot use instance member 'name' within property initializer; property initializers run before 'self' is available
Value of type '[String]' has no member 'name'
structinstead of an array to represent a person. Likestruct Person { let name: String; let role: StringOrEnum, let age: Int, let someEnum: SomeEnumWithGoodOkExcellentEtc}. And you want tofilteror find thefirst(where:). Imagine we have 2 "Paul"s:let paul = array2d.first(where: { $0.first == person }orlet filtered = array2d.filter{ $0.first == person }?struct AView: View {. For your cases, methods and variables they should start with a lowercase letter.case poor = "Poor", ok = "Ok", good = "Good", excellent = "Excellent"SwiftUIis too complex for beginners.