Hi I have a struct like this
struct OrderCaches: Codable {
var food, drink: [Food]?
}
struct Food: Codable{
var id: Int?
var name: String?
var quantity: Double?
var notes: String?
}
I want to get first index where id = productList[indexPath.row].id
I tried with:
let index = OrderCaches.firstIndex(where: {$0.food.id == productList[indexPath.row].id})
but not work I get this error "Value of type '[Food]?' has no member 'id'".
How can I get the first Index?
Thanks
The function firstIndex is not a static member, but an instance member, hence you have to create an instance of OrderCache to get the index, like below:
let orderCaches = OrderCaches(food: [], drink: [])
let index = orderCaches.food?.firstIndex(where: { $0.id == productList[indexPath.row].id })
Related
I have a custom object Shift
struct Shift: Identifiable, Encodable, Equatable {
var id: String = UUID().uuidString
var weekday: String
var startTime: Date
var endTime: Date
}
And an array of Shift objects:
#Published var shifts: [Shift] = []
I would like to remove the last item in the array where the value of weekday is equal to "Monday"
I tried this but it throws an error saying Value of type 'Array<Shift>.Index' (aka 'Int') has no member 'removeLast'
if let index = shifts.firstIndex(where: {$0.weekday == "Monday"}) {
index.removeLast()
}
Any help is appreciated :)
No, you want the last index and you want to remove the item from the shifts array rather than from the index
if let index = shifts.lastIndex(where: {$0.weekday == "Monday"}) {
shifts.remove(at: index)
}
I have an array of working hours, and within that array, there is another array of shifts. I would like to remove all instances in the shifts array where weekday is equal to "Monday"
struct Shift {
let id: String = UUID().uuidString
var weekday: String
var startTime: String
var endTime: String
var error: Bool
}
struct WorkingHours: Identifiable {
let id: String = UUID().uuidString
var availability: [Shift]
}
class AvailabilityManager: ObservableObject {
#Published var workingHours: [WorkingHours] = []
}
In my view:
#EnvironmentObject var availabilityManager: AvailabilityManager
self.availabilityManager.workingHours.removeAll(where: {$0.availability.weekday == "Monday"})
However, it says: "Value of type '[Shift]' has no member 'weekday'"
Any help is appreciated :)
Change
self.availabilityManager.workingHours.removeAll(where: {$0.availability.weekday == "Monday"})
To
self.availabilityManager.workingHours.removeAll(where: {$0.availability.contains(where: {$0.weekday == "Monday"})})
More shorthand method
self.availabilityManager.workingHours.removeAll { $0.availability.contains { $0.weekday == "Monday" } }
Add the following function to WorkingHours
mutating func removeShift(weekDay: String) {
availability = availability.filter { $0.weekday != weekDay }
}
and call it like
workingHour.removeShift(weekDay: "Monday")
If you have an array of WorkinHours you can call the method using map for instance
workingHoursArray = workingHoursArray.map {
var workingHours = $0
workingHours.removeShift(weekDay: "Monday")
return workingHours
}
I am trying to add to an array of maps in Firestore and getting the following error:
Terminating app due to uncaught exception 'FIRInvalidArgumentException', reason: 'Unsupported type: __SwiftValue'
This is my Model Class:
struct StringModel: Identifiable, Codable, Equatable, Hashable {
var id = UUID()
var cross: Int
var mains: Int
var name: String
var date: Date
}
struct UserDataModel: Identifiable, Codable {
#DocumentID public var id: String?
var uid: String
var strings: [StringModel]?
}
Am using the following function to update the value in firestore, however, it doesnt seem to work and throws the error:
#Published var newString = StringModel(cross: 50, date: Timestamp(), mains: 50, name: "")
func addString() {
db.document(uidStr).updateData(["strings" : FieldValue.arrayUnion([newString])]) { err in
if let err = err{
print("\(err)")
}
}
}
Firestore Datatbase
Any ideas how I can go about this? Thanks!
You can't append a Swift object to a Firestore array. You must convert the Swift object into a [String: Any] object. You can add a computed property to the model that outputs this for you.
struct StringModel: Identifiable, Codable, Equatable, Hashable {
var id = UUID()
var cross: Int
var mains: Int
var name: String
var date: Date
var firestoreData: [String: Any] {
return [
"id": id,
"cross": cross,
"mains": mains,
"name": name,
"date": date
]
}
}
func addString() {
db.document(uidStr).updateData(["strings" : FieldValue.arrayUnion([newString.firestoreData])]) { err in
if let err = err{
print("\(err)")
}
}
}
The object definition is:
struct Course: Identifiable, Hashable, Codable {
#DocumentID var id: String?
var country: String
var createdBy: String
}
I then embed this object as a member of a class as so:
class CourseRepository: ObservableObject {
private let path: String = "Courses"
private let store = Firestore.firestore()
#Published var courses: [Course] = []
...
In the snippet below, I only want the map result to contain courses where 'createdBy' == to the uid of the currently logged in user. But on the .filter statement, I get the following error:
emphasized text
**Value of type 'Published<[Course]>.Publisher.Output' (aka 'Array<Course>') has no member 'createdBy'**
MyCourseRepository.$courses
.filter { $0.createdBy == self.authState.loggedInUser!.uid }
.map { courses in courses.map(CourseViewModel.init)}
.assign(to: \.MyCourseViewModels, on: self)
.store(in: &cancellables)
}
Any help on this one much appreciated!
Right now, you're trying to filter the Publisher, whereas what you want to do is filter the items in the array that it's sending:
MyCourseRepository.$courses
.map { courseArray in
courseArray.filter { course in
course.createdBy == self.authState.loggedInUser!.uid
}
}
I have following struct:
struct PalletScan: Codable {
var deliveryId: String?
var userId: String?
var timestamp: String?
var tempPalletNr: String?
var tempLocation: String?
var tempPalletType: String?
var pallets: [MovementScan]?
//coding keys requried for translation API -> struct -> CoreData and CoreData -> struct -> API
enum CodingKeys: String, CodingKey {
case deliveryId = "TOID"
case userId = "UserId"
case timestamp = "TimeStamp"
}
mutating func appendMovementScan() {
var movementScan = MovementScan()
movementScan.locationId = self.tempLocation
movementScan.palletId = self.tempPalletNr
movementScan.palletType = self.tempPalletType
movementScan.timestamp = String(Date().timeIntervalSince1970)
print(movementScan)
self.pallets?.append(movementScan)
}
}
however self.pallets?.append(movementScan) does not adding anything to the pallets array. What am I missing? It must be trivial but can not find mistake.
Just change var pallets: [MovementScan]?
to
var pallets: [MovementScan] = [MovementScan]()
as #Carcigenicate you call append on nil value
var pallet is not initialized and it is an optional so when you append movementscan using ? , it wont be executed.
To fix this you have to some how initialize pallets array before appending to it .
One way can be simply initialize with empty array :
var pallets = [MovementScan]()