How to filter JSON dictionary in SwiftyJSON - swift

I'm using SwiftyJSON to get a list and printing it out to a TableView.
My issue is I can't filter this dictionary, I tried to make a for loop to remove the unwanted elements (or even pushing a new element), but I couldn't find a way to remove or pushing an element with a JSON type that SwiftyJSON provides.
var FilteredTripList:JSON = TripsList
for (key: String, Trip: JSON) in TripsList {
if String(stringInterpolationSegment: Trip["TripFrom"]) != SearchFilter["From"]!
|| String(stringInterpolationSegment: Trip["TripTo"]) != SearchFilter["To"]! {
// I'm hoping for something like the line below
// FilteredTripList[key.toInt()!].remove()
}
}
}

I don't know swifty json, because I always use the native way with NSJSONSerialization... So I have to guess
Please change this line
FilteredTripList[key.toInt()!].remove()
To this line
FilteredTripList.removeValueForKey(key)
And write me what happened

Try something like this:
FilteredTripList.dictionaryObject?.removeValueForKey(key.toInt()!)
It should work.

For me, the best way to filter the [JSON] was doing this:
self.places = self.locals.filter({ (json) -> Bool in
return json["monthlyPurchasesLocalCount"].intValue > 0;
});

Try with the below code snippet if you are using SwiftyJSON,
it works perfectly for me. I got it after a lots of tries.
let jsonObj = some JSON
let jobj = jsonObj.arrayValue
if !jobj.isEmpty {
let j = jobj.filter({ (json) -> Bool in
return json["country"].stringValue == "US"; })
print ("filterdData: \(j)")
}
Note: jobj should be .arrayValue, otherwise it won't work.

Related

How to fix deprecated substring(with: )

I'm working through a book exercise where the author has the following code.
func getMatchingString(str: String) -> String? {
if let newMatch = str.range(of:regExFindMatchString,
options:.regularExpression) {
return str.substring(with: newMatch)
} else {
return nil
}
}
the str.substring(with: newMatch) line shows 'substring(with:) is deprecated use String slicing subscript.'
I've tried to figure out what to use to fix this but everything I've tried shows I just don't understand this well enough to fix it. I know that the newMatch is a range object, just can't figure out how to use it effectively.
Any help is greatly appreciated..
Bob
Just use subscripting with the range you obtain from the if let
if let newMatchRange = str.range(of:regExFindMatchString, options:.regularExpression) {
return String(str[newMatchRange])
} else {
return nil
}
You need to translate it to a String as the method actually returns a Substring type, not a String.

Filter An Array Of Arrays By A Value In Firestore Swift

I'm looking to filter an array of arrays by specific value of one of the keys located within each array. Each nested array is read in from Firestore.
As an object, each nested array would look like this:
struct Video {
var url: String
var submissionDate: Timestamp
var submittingUser: String
}
I'm reading it in like this:
videos = document.get("videos") as? [[String : Any]] ?? nil
So far so good, but when I filter it like this:
filteredVideos = videos.filter { $0[2].contains(self.userIdentification) }
I can't do it without getting the error "Reference to member 'contains' cannot be resolved without a contextual type," an error which I was unable to find any relevant information on SO about.
I have read that some people say "Don't use arrays in Firestore!" but this is a build requirement.
Anyone have any ideas? Basically just need all arrays within the array where userId == submittingUser.
Reference Article:
I tried the answer from here: How to filter out a Array of Array's but no luck for this situation.
It's actually an array of dictionaries, not an array of arrays. All you need to do is construct the right predicate for the filter.
This is basically what your Firestore data looks like:
let videos: [[String: Any]] = [
["url": "http://www...", "submittingUser": "user1"],
["url": "http://www...", "submittingUser": "user2"]
]
This is the user you're looking for:
let userIdentification = "user2"
This is the predicate for the filer:
let filteredVideos = videos.filter { (video) -> Bool in
if let submittingUser = video["submittingUser"] as? String,
submittingUser == userIdentification {
return true
} else {
return false
}
}
You can shorthand this down to a single line if you're okay with force-unwrapping the dictionary (if you're 100% certain every video will have a valid submittingUser value):
let filteredVideos = videos.filter({ $0["submittingUser"] as! String == userIdentification })

How to pass and get multiple URLQueryItems in Swift?

Ok, I am working in an iMessage app and am trying to parse more than 1 url query item from the selected message here- I have been successful getting/sending just 1 value in a query:
override func willBecomeActive(with conversation: MSConversation) {
// Called when the extension is about to move from the inactive to active state.
// This will happen when the extension is about to present UI.
if(conversation.selectedMessage?.url != nil) //trying to catch error
{
let components = URLComponents(string: (conversation.selectedMessage?.url?.query?.description)!)
//let val = conversation.selectedMessage?.url?.query?.description
if let queryItems = components?.queryItems {
// process the query items here...
let param1 = queryItems.filter({$0.name == "theirScore"}).first
print("***************=> GOT IT ",param1?.value)
}
}
When I just have 1 value, just by printing conversation.selectedMessage?.url?.query?.description I get an optional with that 1 value, which is good. But with multiple I cant find a clean way to get specific values by key.
What is the correct way to parse a URLQueryItem for given keys for iMessage?
When you do conversation.selectedMessage?.url?.query?.description it simply prints out the contents of the query. If you have multiple items then it would appear something like:
item=Item1&part=Part1&story=Story1
You can parse that one manually by splitting the string on "&" and then splitting the contents of the resulting array on "=" to get the individual key value pairs in to a dictionary. Then, you can directly refer to each value by key to get the specific values, something like this:
var dic = [String:String]()
if let txt = url?.query {
let arr = txt.components(separatedBy:"&")
for item in arr {
let arr2 = item.components(separatedBy:"=")
let key = arr2[0]
let val = arr2[1]
dic[key] = val
}
}
print(dic)
The above gives you an easy way to access the values by key. However, that is a bit more verbose. The way you provided in your code, using a filter on the queryItems array, is the more compact solution :) So you already have the easier/compact solution, but if this approach makes better sense to you personally, you can always go this route ...
Also, if the issue is that you have to write the same filtering code multiple times to get a value from the queryItems array, then you can always have a helper method which takes two parameters, the queryItems array and a String parameter (the key) and returns an optional String value (the value matching the key) along the following lines:
func valueFrom(queryItems:[URLQueryItem], key:String) -> String? {
return queryItems.filter({$0.name == key}).first?.value
}
Then your above code would look like:
if let queryItems = components?.queryItems {
// process the query items here...
let param1 = valueFrom(queryItems:queryItems, key:"item")
print("***************=> GOT IT ", param1)
}
You can use iMessageDataKit library. It makes setting and getting data really easy and straightforward like:
let message: MSMessage = MSMessage()
message.md.set(value: 7, forKey: "user_id")
message.md.set(value: "john", forKey: "username")
message.md.set(values: ["joy", "smile"], forKey: "tags")
print(message.md.integer(forKey: "user_id")!)
print(message.md.string(forKey: "username")!)
print(message.md.values(forKey: "tags")!)
(Disclaimer: I'm the author of iMessageDataKit)

Swift 3: Change item in dictionary

I'm saving lists in a dictionary. These lists need to be updated. But when searching for an item, I need [] operator. When I save the result to a variable, a copy is used. This can not be used, to change the list itself:
item = dicMyList[key]
if item != nil {
// add it to existing list
dicMyList[key]!.list.append(filename)
// item?.list.append(filename)
}
I know, that I need the uncommented code above, but this accesses and searches again in dictionary. How can I save the result, without searching again? (like the commented line)
I want to speed up the code.
In case you needn't verify whether the inner list was actually existing or not prior to adding element fileName, you could use a more compact solution making use of the nil coalescing operator.
// example setup
var dicMyList = [1: ["foo.sig", "bar.cc"]] // [Int: [String]] dict
var key = 1
var fileName = "baz.h"
// "append" (copy-in/copy-out) 'fileName' to inner array associated
// with 'key'; constructing a new key-value pair in case none exist
dicMyList[key] = (dicMyList[key] ?? []) + [fileName]
print(dicMyList) // [1: ["foo.sig", "bar.cc", "baz.h"]]
// same method used for non-existant key
key = 2
fileName = "bax.swift"
dicMyList[key] = (dicMyList[key] ?? []) + [fileName]
print(dicMyList) // [2: ["bax.swift"], 1: ["foo.sig", "bar.cc", "baz.h"]]
Dictionaries and arrays are value types. So if you change an entry you'll need to save it back into the dictionary.
if var list = dicMyList[key] {
list.append(filename)
dicMyList[key] = list
} else {
dicMyList[key] = [filename]
}
It's a little bit late, but you can do something like this:
extension Optional where Wrapped == Array<String> {
mutating func append(_ element: String) {
if self == nil {
self = [element]
}
else {
self!.append(element)
}
}
}
var dictionary = [String: [String]]()
dictionary["Hola"].append("Chau")
You can try this in the Playground and then adapt to your needs.

Add NSDictionary to existing NSMutableArray - Swift

I have been attempting for a while now to add in an extra dictionary value into a NSMutableArray containing NSDictionaries at each index.
I have tried several approaches detailed below.
func findDistanceAndSortArray(offers : NSMutableArray){
for (index, offer) in enumerate(offers) {
var json = JSON(offer)
if let location = json["company"]["address"]["location"].dictionary {
//Not important Location code is here <-----
var distance = self.calculateDistance(newLat, longitude: newLngg)
var newDistance = ["totalDistance" : distance]
// I have tried these ....
// offers.insertObject(newDistance, atIndex: index)
// offer[newDistance]
// json["totalDistance"] = "" <-- this inserts the dictionary but I cannot add a string into ANYOBJECT
}
println("MORE inside \(json)")
println("MORE inside \(offers)")
}
}
The closest I got was using json["totalDistance"] = "" which inserted the value alongside its key but when I tried to add in the string it produced a error saying can't add string to value type JSON (As I am using SwiftyJson for parsing)
Can't seem to figure this one out but I'm sure its simple.
Thirst: you must not change an array while iterating thru the same array. Because you tried to:
// I have tried these ....
// offers.insertObject(newDistance, atIndex: index)
And the solution should be:
json["totalDistance"].string = distance
Please try, I currently have no compiler to test it.