Find out common value from two different Type Array - ios

I have two Array with different Data Types
Assume Array1 is an [String] array of String
Assume Array 2 is an [Custom Objects] array of Struct
Pls find a code
struct ScanData{
var serialNo : String!
var intNo : String!
init(serialNo : String, intNo : String) {
self.serialNo = serialNo
self.intNo = intNo
}
}
var validScannedData : [String] = []
var inValidScannedData : [String] = []
var arrayObj = [ScanData(serialNo: "12220116033", intNo: "SN6AT4.270"),ScanData(serialNo: "12198144025", intNo: "SN6AT4.280"),ScanData(serialNo: "12222383027", intNo: "SN6AT4.130"),ScanData(serialNo: "12198213032", intNo: "SN6AT5.260"),ScanData(serialNo: "", intNo: "")]
//print(arrayObj)
//ScanData(serialNo: "12199690049", intNo: "SN6AT6U100")
var localArray = ["12220116033","12198144025","12222383027","12198213032","12199690049"]
let tempArray = arrayObj.filter { data in
return data.serialNo != "" || data.intNo != ""
}
print(tempArray.count)
Now we want to get common values from localArray and tempArray by matching serialNo key
Finally i want to have Array of String Format in validScannedData object
Expected Output :
Valid data : ["12220116033","12198144025","12222383027","12198213032"]
Invalid data : ["12199690049"]
I tried this but its prints custom object array
let a = tempArray.filter () { localArray.contains($0.serialNo) }
print(a)
Thanks in advance

Use forEach to iterate your element and then check and append to the according to array.
localArray.forEach { number in
arrayObj.contains(where: {$0.serialNo == number}) ? validScannedData.append(number) : inValidScannedData.append(number)
}
print(validScannedData)
print(inValidScannedData)

Related

Check if an element is present in 3D array Swift

I have an array which gets instantiated in viewDidLoad like var bookingsArray : [[String]] = []
I am adding elements to it in this way:
var configuration: [String] = []
configuration.append(textfieldFacility.text!)
configuration.append((pickSlotTF.text?.components(separatedBy: " ")[0])!)
configuration.append((pickSlotTF.text?.components(separatedBy: " ")[1])!)
bookingsArray.append(configuration as [String])
bookingsArray looks like :
[["A", "20-08-2017", "14:00"], ["B", "20-08-2017", "14:00"]]
While adding new elements to bookingsArray, I want to check if the new element is already present in the array. How do I do it in this case of multi-dimensional array?
First of all, if you want unique objects use a Set.
If this is not possible I highly recommend to use a custom struct which can conform to Equatable rather than a nested array , for example
struct Booking : Equatable {
let facilty : String
let date : String
let time : String
static func ==(lhs : Booking, rhs : Booking) -> Bool {
return lhs.facilty == rhs.facilty && lhs.date == rhs.date && lhs.time == rhs.time
}
}
Then declare the array as
var bookingsArray = [Booking]()
and create an object with
let dateArray = pickSlotTF.text!.components(separatedBy: " ")
let configuration = Booking(facility: textfieldFacility.text!,
date: dateArray[0],
time = dateArray[1])
bookingsArray.append(configuration)
The huge benefit is that you can easily check
if bookingsArray.contains(item)
You can simply search for it with contains().
var configuration: [String] = []
configuration.append(textfieldFacility.text!)
configuration.append((pickSlotTF.text?.components(separatedBy: " ")[0])!)
configuration.append((pickSlotTF.text?.components(separatedBy: " ")[1])!)
if !bookingsArray.contains(where: {$0 == configuration}) {
bookingsArray.append(configuration)
}

Filtering Arrays Containing Multiple Data Types in Swift3

I have an array like:-
var arrayData : Array<Dictionary<String, [BottleModel]>> = []
Bottle model :-
class BottleModel: NSObject {
var name : String
var price : Int
var reviews : Int
var category : String
var quantity : String
var id : String
var shopData : ShopModel
}
I want filtered array where price is > 2000
I tried let searchByInts = arrayData.filter({m in m.price < 200})
but getting below error:
Contextual closure
type '(Dictionary) -> Bool' expects 1 argument,
but 0 were used in closure body
How to filter such kind of array based on price
Working code:
let searchByInts = arrayData.filter { $0.values.contains { $0.contains { $0.price > 2000 } } }
By the way please write the following using literals:
var arrayData : [[String : [BottleModel]]] = []
Still no idea if that is what you actually want because your goal is very unclear. You have an array of dictionaries of arrays which actually contain the values you want to filter out. If a BottleModel costs more than 2000 do you want to keep the entire array it is contained in and the dictionary that array is in? You might want to map the entire data into one flat array before or after filtering.
Alternative using flatMap:
let flat = arrayData.flatMap { $0.values.flatMap { $0 } }
let searchByInts2 = flat.filter { $0.price < 200 } // or some other criteria

Swift:How to map a single key to Multiple values?

I have successfully mapped a Single key to single value like this:
class DefaultDoubleModel :BaseObject
{
var key : String = ""
var value : String = ""
}
var toolChart :[DefaultDoubleModel]!
self.BubbleChartXaxislabel = Array(GraphDataModel.toolChart.map({ (item) -> String in
item.key
}))
self.BubbleChartValuesGraph = Array(GraphDataModel.toolChart.map({ (item) -> String in
item.value
}))
This is true for single key and single value. But i have two values in a single key. How can i collect those values in array.
For example i have like this..
{"value2":"80","value1":"120","key":"4"}
A Dictionary with tuples of strings would look like this:
var data: [String: (String, String)]()
data["4"] = ("80", "120")
print(data["4"]!.0)
You access the elements as .0 and .1.
If you want exactly two values, then you can make your DefaultDoubleModel look like this
class DefaultDoubleModel :BaseObject {
var key : String = ""
var value1 : String = ""
var value2 : String = ""
}
I think its more future proof to make it an array of Strings, like this:
class DefaultDoubleModel :BaseObject {
var key : String = ""
var values = [String]()
}
If you go with the second option, then you would map like this:
self.BubbleChartValuesGraph = GraphDataModel.toolChart.flatMap{ $0.values }

Cannot add an append an array into a dictionary that has an empty array

I have a Profile Data singleton class as follows.
I am trying to store data into an empty array in a dictionary .
After appending data to the array also the count of the array is 0.
class ProfileData{
static let sharedInstance = ProfileData()
var artistProfileDict = [String : Profile]()
var loggedInUserProfile = Profile(artistName: "John Smith", artistDescription: "Admiral of New England, English soldier, explorer, and author.", totalLikes: "174", totalViews: "200", totalFollowing: "100",totalFollowers:"50",imageUrl:"image_singer", feeds:[] )
private init() {
getProfilesDictionary()
}
func getProfilesDictionary()->[String: Profile]{
artistProfileDict["John Smith"] = loggedInUserProfile
return artistProfileDict
}
func add(array: Feed, artistName: String) {
artistProfileDict[artistName]!.feeds.append(array)
}
}
In another view Controller I am trying to add an array to the empty array in the dictionary as follows
let newFeed = Feed(profilePicture: "image",artistName: "New",
videoUrl: "url",videoTitle:"New", videoViews: "160",likes:
"200",shoutouts: "200",comments: [],votes: "50", dateCreated: Date(),
userActivity :"This user liked your video")
ProfileData.sharedInstance.add(array: newFeed,artistName:"John Smith")
After appending the array to the empty array in the dictionary I still get the count of the array as 0.
I am not able to figure out the problem here. Any help will appreciated . Thank you.
Profile class
struct Profile {
var artistName: String
var artistDescription: String
var totalLikes: String
var totalViews: String
var totalFollowing: String
var totalFollowers: String
var imageUrl: String
var feeds : [Feed]
init(artistName: String,artistDescription:String,totalLikes:String,totalViews:String,totalFollowing:String,totalFollowers:String,imageUrl:String, feeds:[Feed]) {
self.artistName = artistName
self.artistDescription = artistDescription
self.totalLikes = totalLikes
self.totalViews = totalViews
self.totalFollowing = totalFollowing
self.totalFollowers = totalFollowers
self.imageUrl = imageUrl
self.feeds = feeds
}
}
It's working fine
ProfileData.sharedInstance.add(array: newFeed,artistName:"John Smith")
ProfileData.sharedInstance.artistProfileDict["John Smith"]?.feeds.count // 1
Probably you are using wrong class ArtistProfileData instead of ProfileData.

Swift: How to add dictionary arrays to an array?

Can I add dictionary arrays (is this the correct term for a dictionary key holding multiple values?) to an array?
var dictionary = [String: [String]]()
var array = [String]()
var data1:String = "55a"
var data2:String = "95a"
var data3:String = "66"
var data4:String = "25"
var data5:String = "88b"
var data6:String = "#"
dictionary["3"] = [data1, data2, data3, data4, data5, data6]
var data7:String = "#"
var data8:String = "#"
var data9:String = "#"
var data10:String = "#"
var data11:String = "#"
var data12:String = "#"
dictionary["2"] = [data7, data8, data9, data10, data11, data12]
var data13:String = "100"
var data14:String = "101"
var data15:String = "102"
var data16:String = "103"
var data17:String = "104"
var data18:String = "105"
dictionary["1"] = [data13, data14, data15, data16, data17, data18]
I tried this:
array.extend([dictionary["1"], dictionary["2"], dictionary["3"]])
but there was an error "Cannot invoke 'extend' with an argument list of type '([[(String)?])"..
How do I add dictionary["1"], ["2"] & ["3"] accordingly into the array?
Your array type declaration is not correct. Please try below one
var array: [[String:[String]] = []
In case you are not interested in the order you might try:
array.extend(flatMap(dictionary.values, {$0}))
If order is important you might build your optionalArrays first:
let optionalArrays = [dictionary["1"], dictionary["2"], dictionary["3"]]
array.extend(flatMap(optionalArrays, {$0 ?? []}))
i.e. your dictionary returns an optional array, this causes the error you reported.
Hope this helps
If you wanted an array of arrays of Strings, you need to change your array's type to be [[String]], as the other answers said.
But, when getting values out of your dictionary, you shouldn't force unwrap! It may work for this example, but in the future you'll likely get into trouble with:
'fatal error: unexpectedly found nil while unwrapping an Optional
value'
You should check to see if a value exists in the dictionary for that key, using optional binding for example:
if let value = dictionary["1"] {
array.append(value)
}
// ...
Or, you could get all the values from your dictionary into an array like so:
let array = Array(dictionary.values)
If you actually did want an array of Strings, you could use flatMap:
let array = flatMap(dictionary.values) { $0 }
Your array variable must be an Array of Array with String elements.
Also don't forget to unwrap the values of the dictionaries by adding !.
Try this:
var dictionary = [String: [String]]()
var array = [[String]]()
var data1:String = "55a"
var data2:String = "95a"
var data3:String = "66"
var data4:String = "25"
var data5:String = "88b"
var data6:String = "#"
dictionary["3"] = [data1, data2, data3, data4, data5, data6]
var data7:String = "#"
var data8:String = "#"
var data9:String = "#"
var data10:String = "#"
var data11:String = "#"
var data12:String = "#"
dictionary["2"] = [data7, data8, data9, data10, data11, data12]
var data13:String = "100"
var data14:String = "101"
var data15:String = "102"
var data16:String = "103"
var data17:String = "104"
var data18:String = "105"
dictionary["1"] = [data13, data14, data15, data16, data17, data18]
array.extend([dictionary["1"]!, dictionary["2"]!, dictionary["3"]!])
Dictionary values are returned as optionals (thus indicating if a value exists for a key) so use the '!' to unwrap the values of each dictionary array (i.e. [dictionary["1"]!)
And as suggested in other answers change your array type as it currently defined as arrays of string rather then an array of dictionaries.

Resources