Get indexOfObject method without using Foundation objects - arrays

by selecting 1st tableView row/section I want to check if selected item already in 2nd tableView ?, if yes then find that selected item indexOfObject in 2nd tableView.
NSInteger sectionIndex = [[allSelectedProducts valueForKey:#"productID"] indexOfObject:[allProductData[indexPath.section] valueForKey:#"productID"]];
this will return the index of selected object in allSelectedProducts, Returns the lowest index whose corresponding array value is equal to a given object.
I want to perform this same task in swift, how can I achive that !
In Swift I've taken allSelectedProducts for 1st tableView and allProductData for 2nd tableView both arrays with Array<Dictionary<String, Any>> type
I want to perform this task without using Foundation classes, can we perform that same task in array using indexOf in Swift !?
let productIndex = allSelectedProducts.indexOf(<#T##predicate: ([String : Any]) throws -> Bool##([String : Any]) throws -> Bool#>)
If we can, then how ?
please guide me how to use indexOfin swift
thanx in advance for any help

Probably something like this:
let searchedProductID = allProductData[indexPath.section]["productID"]
let index = allSelectedProducts.indexOf { $0["productID"] == searchedProductID }
which is a direct translation of your original code

Related

Swift: How do you use a variable in an array?

I am using a pod called iOSDropDown to display a dropdown selection menu for a textfield. I am getting a list of data from php to populate that selection menu that Im storing in a variable.
The PHP data passed stored in a swift variable looks like this when printed -> "option01","option02","option03"... and so on. This is dynamic data that will change that is why I am retrieving from PHP/MYSQL Database instead of just manually typing in the options in the Swift array.
Below is my code. What I am trying to do is use the "dropdownData" variable that holds the options for the array. Each option should be in its own row and separately selectable. What I am getting is one option, one string of coding with all my options as shown in the picture below.How would I use the dropdownData variable to display options instead of one string, one option?
dropdownData = "option01","option02","option03"... etc. ALL OPTIONS STORED IN THIS ONE ARRAY
let dropdownData : String = (dumpsArray[indexPath.row] as AnyObject).value(forKey: "dropdownData") as! String
.
cell.nameField.optionArray = [dropdownData]
Image
In the image above there should be no comma after styrofoam cooler... the next product should be the next option displaying under the styrofoam cooler and separately selectable.
Seems like dumpsArray[indexPath.row] as AnyObject).value(forKey: "dropdownData") returns a String where names are comma separated,
so
if let nameString = dumpsArray[indexPath.row] as AnyObject).value(forKey: "dropdownData") as? String {
let namesArray = nameString.components(separatedBy: ",")
cell.nameField.optionArray = namesArray
}
That should do

Kotlin Array with named parameter equivalent of swift

Hi i'am new to Kotlin and i would like to do an array with named parameter. In Swift i can do :
let analytics = ["organization_login": "toto", "organization_name": "titi", "lead_email": "tata"]
The type is : [String: String]
I Looked all Array and Arraylist in kotlin but i couln't find the equivalent.
What i want it's to be able to give parameter name for my array.
Edit
I misunderstood the swift syntaxe, it's seem that it's only a dictonary, so we just have to use map.
The reason is that [String: String] is not an array, it's a Dictionary.
The equivalent of Dictionary in Kotlin is Map.
Maps can be created like so:
val map = mapOf("string_one" to "string_2", "string_3" to "string_4")
or, if you want to mutate it:
val mutableMap = mutableMapOf("string_one" to "string_2")
You need to use Map as
val map = mapOf("organization_login" to "toto", "organization_name" to "titi")
// immutable map
you can also use sortedMapOf, hashMapOf linkedMapOf etc for different algo based storage.
Note: If you want to add more elements later then make sure to use mutableMapOf

Swift 3 - set the key when appending to array

I have this array where I set the keys on the creation. Now in some point in my view I load some more information based on ids (the keys).
var colors = [
"37027" : UIColor(red:150/255, green:57/255, blue:103/255, alpha:1),
"12183" : UIColor(red:234/255, green:234/255, blue:55/255, alpha:1),
"44146" : UIColor(red:244/255, green:204/255, blue:204/255, alpha:1)
]
I want to add more colors to this array dynamically. How can I insert new items in the array setting the key? Something like
colors["25252"] = UIColor(red:244/255, green:204/255, blue:204/255, alpha:1)
The line above doesn't work, it is just to illustrate what I need.
Thanks for any help
Update: the code above is an example. Below the real code:
var placedBeacons : [BeaconStruct] = []
BeaconModel.fetchBeaconsFromSqlite(completionHandler: {
beacons in
for item in beacons{
self.placedBeacons["\(item.major):\(item.minor)"] = item
}
})
Error: Cannot subscript a value of type '[BeaconStruct]' with an index of type String
To match the key subscripting
self.placedBeacons["\(item.major):\(item.minor)"] = item
you have to declare placedBeacons as dictionary rather than an array
var placedBeacons = [String:BeaconStruct]()
It requires that item is of type BeaconStruct
The code you wrote, it should work. I have used such kind of code and was able to implement successfully. I just tested your code in my end and it's working for me. I declared colors variable globally in my class file and in view did load method added the second code to add another item in my colors array. After printing it out. My output shows full list of array with 4 items and the number of array count return 4 as well.
Please let me know, more details of your scenario so i can help you to figure it out the issue. but looks like it should work.

Parse.com Query with swift 1.2 and string array

I am trying to query from parse.com and I would db receiving about 100 objects per time. I used the swift example code on their website, and the app doesn't build with that code. So I looked around and found that people were using code similar to this:
var query = PFQuery(className:"posts")
query.whereKey("post", equalTo: "true")
query.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]?, error: NSError?) -> Void in
// do something
self.myDataArray = objects as! [String]
})
This does not work, because I am trying to convert PFObject to String
I would need to get the one one value from each object into a swift string array [String]. How do I get just the one text value, instead of the PFObject and how do I get it into the swift string array?
I don't speak swift very well, but the problem with the code is it's trying to cast the returned PFObject to a string, but you want to extract a string attribute, so (if you really want to do it):
for object in objects {
var someString = object.valueForKey("someAttributeName") as String
self.myDataArray.addObject(someString)
}
But please make sure you need to do this. I've noticed a lot of new parse/swift users (especially those who are populating tables) have the urge to discard the returned PFObjects in favor of just one of their attributes. Consider keeping the PFObjects and extracting the attributes later as you need them. You might find you'll need other attributes, too.
For starters, I would definitely recommend using the "if let" pattern to qualify your incoming data. This is a nice Swift feature that will help avoid run-time errors.
var query = PFQuery(className:"posts")
query.whereKey("post", equalTo: "true")
query.findObjectsInBackgroundWithBlock(
{ (objects: [AnyObject]?, error: NSError?) -> Void in
// check your incoming data and try to cast to array of "posts" objects.
if let foundPosts = objects as? [posts]
{
// iterate over posts and try to extract the attribute you're after
for post in foundPosts
{
// this won't crash if the value is nil
if let foundString = post.objectForKey("keyForStringYouWant") as? String
{
// found a good data value and was able to cast to string, add it to your array!
self.myDataArray.addObject(foundString)
}
}
})

Empty Array in Swift?

I am trying to create an empty array in Swift that the user adds on to. It is a very small class because I am just starting a new file. I am using this tutorial for my project which is what the code is based off. Here is the code I tried (It didn't work):
var tasks = task[]()
Here is all of my code in case it is needed:
class TaskManager: NSObject {
var tasks = task[]()
func addTask(name: String){
tasks.append(task(name: name))
}
}
There is an error on the var tasks = task[]() line saying: "Array types are now written the brackets around the element type". I am unsure of how to fix the problem.
How can one create an empty array?
Any input or suggestions would be greatly appreciated.
Thanks in advance.
You have to declare the array in this way:
var tasks = [task]()
It changed in swift from the tutorial you are watching.
The syntactic sugar for an array of Type is [Type] in Swift. You can create an empty array of Tasks like this:
class Task{}
var tasks = [Task]()

Resources