in my app, I get an array from an API
do {
var data = try JSONDecoder().decode([NameInfo].self, from: data!)
data.sort{$0.updated_at! > $1.updated_at!}
completion(.success(data))
} catch {
print(error)
}
for example in this data contains about 600 items which take a long time to load in the app, I just want to reduce the size of this array to 50 items directly here that this reduced array goes to the app to show.
I tired to use this method
let limitedData = data.prefix(50)
completion(.success(limitedData))
but this error shows up:
Member 'success' in 'Result<[NameInfo], Error>' produces result of
type 'Result', but context expects
'Result<[NameInfo], Error>'
Could anyone help me on that?
Thanks
Your Result expects [NameInfo] as Success type. prefix() method returns ArraySlice<NameInfo>. You need to create array from your limitedData:
let limitedData = data.prefix(50)
completion(.success(Array(limitedData)))
Related
I just wanna get all the records from the transaction variable and save it to an array.i tried and all I am getting is this constant error. please help me, I just wanna all models(records) to be saved on an array.
Type '()' cannot conform to 'View'
#State private var transactions: [Transactions] = [Transactions]()
ForEach(transactions, id: \.self) { transaction in
timexxx[0] = transaction.timexx ?? "0"
Text(timexxx[0] ?? "0")
}
enter image description here
Like what #multiverse has suggested
ForEach loop expects some sort of View but you are giving it or attempting to give an "array" (it only wants View)
Here is an updated code where you give the ForEach what it wants and you append to your timexxx array
ForEach(Array(transactions.enumerated()), id: \.offset) { (offset, transaction) in
Text(transaction.timexx ?? "\(offset)")
.onAppear {
timexxx[offset] = transaction.timexx ?? "\(offset)"
}
}
Update
for your question
"how do I do this with a simple "For" loop ? let's say I wanna do this operation in a simple class."
This is how it's done.
I removed the view Text.
for (i, transaction) in transactions.enumerated() {
timexxx[i] = transaction.timexx ?? "0"
}
Ok , so this is an error i faced as well, when i was learning SwiftUI( i am still a beginner), so now we need to understand , what does this error actually means, in this case the ForEach loop expects some sort of View but you are giving it or attempting to give an "array" (it only wants View)....
If you want values to be transferred to an array just simply create a function and do it .....
say you have a class and inside of which you do
#Published var song = [Song]()
then what you do is inside a function like loadData()
objects is the array whose elements you want transferred and most likely those elements belong to a Struct like Song here(if not its even simpler just use what ever type it has like Int, String etc.), this way all your elements will get transferred to song from objects
func loadData() {
song = objects.map {
artist in
Song(album: artist.album, artistImage: artist.artistImage)
}
}
Here i add the simplest possible way to transfer from one array to other
var objects = [1,2,3,4,5]
var song = [Int]()
func loadData() {
song = objects.map { $0 }
}
loadData()
print(song)
//[1,2,3,4,5]
I have a document in Firebase Firestore like the above picture, i want to modify a single element in "order" array, i know there is no direct way to do it but is there any way?
i tryed the below code
let ww = db.collection("collectionName").document("docName")
let arrayElement = 0
ww.updateData([
"order.\(arrayElement).isHasOffer": true,
"order.\(arrayElement).referenceID": self.referenceID,
"order.\(arrayElement).DosageForm": "dd",
"order.\(arrayElement).GenericName": "test",
"order.\(arrayElement).DISC": 33
]) { err in
if let err = err {
print("Error updating document: \(err)")
} else {
print("Document successfully updated")
}
}
it's override "order" array (remove all the element and adding only what i pass in the code) -> what if there is 100 elements? should i rewrite them all again
it's also convert it from "Array" type to "map", once converted to "map" i'm not able to read them back as an array
note: i have a unique id for every element in the array
Whenever you want to modify individual elements of an array type field, you have to read the document, modify the array in memory, then update the modified array back to the document.
You will not be able to do this without reading the document first. If you require an atomic update, you can perform this read-then-update procedure in a transaction.
I have Java service which retrieves table from oracle database and I want to display the result in Angular application, also I have an array of Objects in Angular:
resultSet:Info[]=[];
service:
pastHourInfo() {
const url='/SearchApp-1.0/users/transaction';
return this.http.get(url).pipe(map((data:any)=>data));
}
this is my service subscribtion:
checkPasHourInfo() {
this.searchService.pastHourInfo().subscribe(data => {
console.log("we got: ",data);
this.resultSet.push(data);
console.log(this.resultSet.length);
},
error => {
console.log("Error",error);
},);
Problem is the next. The result is 77 rows .
console.log("we got: ",data) gives correct result. you cans see it here
but console.log(this.resultSet.length); prints "1" when it must be 77.
What is the problem?
From your screenshot it seems that your are pushing the array into your result array, you could spread your data into the array as such:
this.resultSet.push(...data);
You are pushing an array into an array. So your array looks like this
resultSet[].length = 1;
resultSet[0].length = 77;
Instead of doing:
this.resultSet.push(data);
try this:
this.resultSet.concat(data);
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
You can add array into another array as below:
this.resultSet.concat(data)
I am trying to access the following data in Vue.js
{"id":1,"name":"Westbrook","created_at":"2017-06-10T16:03:07.336Z","updated_at":"2017-06-10T16:03:07.336Z","stats":[{"id":1,"player_id":1,"points":2558,"assists":840,"rebounds":864,"created_at":"2017-06-10T16:03:07.373Z","updated_at":"2017-06-10T16:03:07.373Z"}]}
self.player = response.name works. now i need self.point
methods: {
fetchData: function() {
var self = this;
$.get("api/v1/players/1", function(response) {
console.log(response);
self.player = response.name;
self.point = response.stats.points
});
}
}
I have thus far tried response.stats["points"], response.stats[2], response.stats[ { points } ], response.stats[points]
The stats property in your json holds an array in which the first object has a property named points
So use response.stats[0].points
Keep in mind though that the stats is probably an array for a reason. It might hold more than one objects in the future, so always using the first element [0] might not be a valid approach.
I think it can help you
var json = JSON.parse(data);
json.stats[0].points
response = {"id":1,"name":"Westbrook","created_at":"2017-06-10T16:03:07.336Z","updated_at":"2017-06-10T16:03:07.336Z","stats":[{"id":1,"player_id":1,"points":2558,"assists":840,"rebounds":864,"created_at":"2017-06-10T16:03:07.373Z","updated_at":"2017-06-10T16:03:07.373Z"}]}
If you want to access the name
console.log(response.name) // Westbrook
If you want to access the stats data which contain list, simply target
let stats=response.stats[0] //By getting the first index in the list
Get the points in stats
console.log(stats.points) // 2588
Can someone please help me with this. I saved my data into Parse.com into column with type array (example: ["11:30","12:45,"13:02"], just some list of some times as string). I have tried to get this data with swift:
var take: NSMutableArray!
var query = PFQuery(className: "test")
query.getObjectInBackgroundWithId("QZ6Y8Oljc5"){
(testData: PFObject!, error: NSError!) -> Void in
if (error == nil){
take = testData["workday"]
println(take)
}
else{
println(error)
}
}
the problem is that i get only json array type:
(
"11:30",
"12:45,
"13:02"
)
How can I convert it into NSArray so it could be like:
var myArray = ["11:30","12:45,"13:02"]
Thank you for any suggestions because I tried every method I found here, but without any results.
The problem with JSON data is that it is it's own array that has to be sifted and groomed. normally people would end up using huge nested IF statements which ends up looking messy. Luckily, someone created a code that sifts through JSON data and gives you back usable types (Int, Arrays, Strings) by use of a massive switch table.
https://github.com/SwiftyJSON/SwiftyJSON
Look it up, it should help. Once you have it implemented you can call it by typing..
let json = JSON(Data : JSONData)
then to sift through, you use substrings.. (depending on the data, you match it with a string or int)
let firstIndex = json["workday"]
//Int
let firstIndexOfWorkDay = json["workday"][0]
//String
let firstIndexOfWorkDay = json["workday"]["time"]
and so on... however, you will need to cast it once you singled out the data
let firstIndexOfWorkDay = json["workday"][0].valueOfFloat
//printing it would give 11:30
although personally I use ".description" .. since sometimes when I sift through all the array, its a mix of types.
let firstIndexOfWorkDay = json["workday"][0].description
println(firstIndexOfWorkDay)
//would literally give "11:30" including the quotation marks
then I use string methods to trim the quotations then cast it to whatever type I need. But it's up to your creativity once you figure out how it works