return random dictionary items in swift - ios

I'm trying to return a random name and a random email from this function have got so far but I'm wondering what should I be returning here obviously as I want to return a tuple it needs to be 2 string values which I need randomly from my function
func randomAuthor () -> (name : String, email : String) {
struct Author {
var name : String
var email : String
}
let firstAuthor = Author(name: "jon", email: "jonsEmail")
let secondAuthor = Author(name: "richard", email: "richardsEmail")
let thirdAuthor = Author(name: "steve", email: "stevesEmail")
let fourthAuthor = Author(name: "simon", email: "simonsEmail")
let fifthAtouh = Author(name: "wes", email: "wesEmail")
var dictionary = [firstAuthor.name : firstAuthor.email, secondAuthor.name : secondAuthor.email, thirdAuthor.name : thirdAuthor.email, fourthAuthor.name : fourthAuthor.email, fifthAuthor.name : fithAtouh.email]
var unsignedDictionaryCount = UInt32(dictionary.count)
var unsignedRandom = arc4random_uniform(unsignedDictionaryCount)
var random = unsignedRandom
return()
}
any help appreciated
thanks

Random value from an Dictionary in several steps:
Create your Dictionary
Get a random Int using arc4random_uniform
Used this random Int to get a random key (using keys), and get its value
Return them, and you are done !
var dictionary : [String:String] = [firstAuthor.name : firstAuthor.email, secondAuthor.name : secondAuthor.email, thirdAuthor.name : thirdAuthor.email, fourthAuthor.name : fourthAuthor.email]
let index: Int = Int(arc4random_uniform(UInt32(dictionary.count)))
let value = Array(dictionary.values)[index]
let key = Array(dictionary.keys)[index]
let value = dictionary[key]
return (key, value!)

Use your random integer as an index into dictionary.keys. This will fetch you the name that you can use to look up your email.

Related

Find out common value from two different Type Array

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)

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.

How to update Firebase with struct

I have a struct EventDate and am trying to update a reference in Firebase.
struct EventDate {
var club: String = ""
var date: String = ""
var eventText: String = ""
var free: String = ""
var monthYear: String = ""
}
My update function throws lldb. I guess because the keys are no Strings(?)
func updateEvent(_ backendlessUserObjectID: String, event: EventDate) {
let reference = firebase.child("eventDates").child(backendlessUserObjectID).child(event.date)
reference.setValue(event) { (error, ref) -> Void in
if error != nil {
print("\(error)")
}
} // lldb here
}
If I change the function to the following, everything is fine (because Keys and Values are now Strings?)
func updateEvent(_ backendlessUserObjectID: String, event: EventDate) {
let item: NSMutableDictionary = ["club" : event.club,
"date" : event.date,
"eventText" : event.eventText,
"free" : event.free,
"monthYear" : event.monthYear]
let reference = firebase.child("eventDates").child(backendlessUserObjectID).child(event.date)
reference.setValue(item) { (error, ref) -> Void in
if error != nil {
print("\(error)")
}
}
}
Am I right that I receive lldb because the keys from my models are not Strings? Or what am I missing and how will I be able to save the values into my Firebase using my model without creating the NSMutableDictionary? Help is very appreciated.
PS: print(event.date) = 201610120200000000 -> the desired value for .child
Firebase data exists in a JSON format which can be thought of as key:value pairs. The keys must be strings and the values can be any of the for data types mentioned in Dravidians answer (which is a correct answer and should be accepted). I would like to add some additional comments that may help as well.
There are times when you want to use a structure in code and that can't be written to Firebase directly - you need some way to get the data out of the structure into something Firebase likes - which is a Dictionary.
Heres an example (Swift 3, Firebase 2.x)
struct EventDate {
var club: String = ""
var date: String = ""
var eventText: String = ""
var free: String = ""
var monthYear: String = ""
func getDict() -> [String:String] {
let dict = ["club": self.club,
"date": self.date,
"eventText": self.eventText,
"free": self.free,
"monthYear": self.monthYear
]
return dict
}
}
var event = EventDate()
event.club = "Wimbledon"
event.date = "20161023"
event.eventText = "Special Tennis Event"
event.free = "Free"
event.monthYear = "10/2016"
let ref = self.myRootRef.child(byAppendingPath: "events")!
let eventRef = ref.childByAutoId() //Firebase 2.x
eventRef?.setValue( event.getDict() )
This results in a node being written to Firebase that looks like this
"events" : {
"-KUli8oiM_KKw8GZ0MMm" : {
"club" : "Wimbeldon",
"date" : "20161023",
"eventText" : "Special Tennis Event",
"free" : "Free",
"monthYear" : "10/2016"
}
}
No it has nothing to do with the type of keys that you are trying to save in your Firebase Database its just that struct is a dataModel or to be precise a physically grouped list of variables which you initialise with some custom Data, and you can only save four types of values types in your Firebase Database:-
NSDictionary
NSArray
NSNumber
NSString
Look up the docs :- Read And Write data, Firebase- iOS
So when you cast your values in a NSMutableDictionary, you come clean of struct. And struct and class is not recognisable by the Firebase Database.

How to find the index of an item in an array of class in Swift?

Well first of all we all know that finding an index of an array is easy but I got stump finding an index of an item in an array which contains multiple structs.
This is my class:
class Patient{
private var id: Int
private var name: String
private var gender: String
private var mileage: Double
//global variable
var globalPatientID:Int{
return id
}
var globalPatientName:String{
return name
}
var globalPatientGender:String{
return gender
}
var globalPatientMileAge:Double{
return mileage
}
init(id:Int, name:String, gender:String, mileage:Double){
self.id = id
self.name = name
self.gender = gender
self.mileage = mileage
}
}
This is my array:
let AppUserID = prefs.objectForKey("AppUserID")
for var i=0; i<nou; ++i{
numberOfUsersExisting = nou
if (AppUserID as? String == json[0][i]["App_ID"].stringValue){
print("Assigning AppUserID")
appUserMileage = json[0][i]["Mileage"].doubleValue
}
pSample += [Patient(id: json[0][i]["ID"].intValue, name: json[0][i]["Name"].stringValue, gender: json[0][i]["Gender"].stringValue, mileage: json[0][i]["Mileage"].doubleValue)]
pSample.sortInPlace({$0.globalPatientMileAge < $1.globalPatientMileAge})
}
So pSample is initially a blank array and it appends a class of items through a loop.
The sortInPlace function helps me to sort pSample based on globalPatientMilaAge.
So this got me thinking, how do I get the index of my AppUserID(which I cast it as a String) from the array of class?
I tried using this function but it doesn't seems working because I'm looping through classes instead of items inside a class.
appUserRanking = pSample.indexOf("\(AppUserID)")
The body of indexOf can be a closure like the map and filter functions
appUserRanking = pSample.indexOf{$0.globalPatientID == AppUserID}
PS: It's pretty inefficient to get one object from json (json[0][i]) 6 times in the repeat loop.
Assign the object to a variable
let object = json[0][i]
and use it for example
if (AppUserID as? String == object["App_ID"].stringValue){
Do like this,
let pSampleFiltered = pSample.filter {$0.globalPatientID == AppUserID}
if pSampleFiltered.count > 0 {
if let index = pSample.indexOf(pSampleFiltered.first!) {
// Do your stuff here
}
}
In Swift 3 and above mapping works like this
appUserRanking = pSample.index(where: {$0.globalPatientID == AppUserID})

Resources