Swift 3: can you store code in variable then run it on tableview load? - ios

I have created a UITableView that pulls data from php mysql and passes data back in JSON format. In one of my variables passed in JSON format it's going to contain the value of:
variable = "cell.username.text = signupDate as String"
Is it possible and if so how would I run this variable so that its value '"cell.username.text = signupDate as String"` would run like it normally would if it wasn't inside the variable?
I hope this makes sense and any help would be appreciated. Thanks.
What Im Specifically Trying To Accomplish
MySQL : Data stored as interests separated by commas.
Ex: "Outdoors, Coding, Videogames, etc."
Reformat Interest in PHP : Before sent as JSON to swift I will reformat interests
Note: I am using a cocoa pod called Tag List View
interests variable = "cell.interestsTag.addTag(“ Outdoors”); cell.interestsTag.addTag(“ Coding”); cell.interestsTag.addTag(“ Videogames”);"
Swift3 : Receive JSON variable as
var variable : NSString = (membersArray[(indexPath as NSIndexPath).row] as AnyObject).value(forKey: "variable") as! NSString
when I print variable I get exactly what I want:
cell.interestsTag.addTag(“ Outdoors”); cell.interestsTag.addTag(“ Coding”); cell.interestsTag.addTag(“Videogames”);
This is code inside the variable that needs to be run inside of my tableviewcell. Just can't figure out how to run the variable so it runs the code inside. If its even possible.

Related

Qmetry- How to store and access Array of array list of strings

In Qmetry,Trying to save array of arraylist string and access same in another test case.
Array of array list :
ArrayList<ArrayList<String>> my_list
store(my_list, "array_list_1");
//Accessing saved list
Object list_details = getBundle().getObject(array_list_1);
System.out.println("++++ saved list details++++" + list_details);
I am able to print list_details content. Till this there is no issue. But when I try to get the first index within the arraylist, not able to use .get(0) method. Below is the code.
ArrayList<String> list_details1 = list_details.get(0);
When tried typecasting , got an error 'java.lang.String cannot be cast to java.util.ArrayList'
typecast:
ArrayList<ArrayList<String>>list_details1 = (ArrayList<ArrayList<String>>)list_details;
Need to know is it the right way to store and access arraylist ? Please suggest.
if you want store in file, you can use .csv or .xls to save ArrayList<ArrayList> my_list, if ArrayList<ArrayList> my_list you query from database, you can set as static variable, then you can use in different method

Array of object append not working on swift [duplicate]

I am currently having trouble filling up an array of customClass.
I try to fill it with a jsonFile. During my json parsing (using swiftyJSON) i loop and fill my array.
The problem is, at the end of my loop, it is still empty. I tested it in different ways, and here is my code:
That's the file where the problem is. In my loop I fill an Annotation, that I add with append to my array. The problem is what my print return. Here is a part of it:
It's just a small part of a huge jsonfile. And, my tmpAnnot.name is correctly printed every iteration. But when it comes to my Array, nothing.
So I'm completly lost and hope you could help me ^^
(And for the information, here is my custom class) :
And btw, I tried to print my array.count, and it's nil too
Im so sorry if the question has been posted. I couldn't find it in the entire website.
Change your JSONAnnotationList declaration to be an non-optional and assign it an empty array
var JSONAnnotationList: [UGOAnnotation] = []
You see, you have never created an array so there was nothing to be printed.
The whole point of optionals is to use them sparingly, not everywhere.

Update dictionary with previously deleted items

I have two dictionaries. Both declared in a viewController, both based on a model structure class.
// ItemDictionary
var ItemDictionary = ItemModel()
var JSONDictionary = ItemModel()
JSON data is fed into the JSONDictionary and then this data is passed to ItemDictionary which feeds a table within ViewDidLoad.
self.ItemDictionary = self.JSONDictionary
All good. The table is nicely populated from JSON data. I can also delete items from the table and the ItemDictionary. However, when I try and add items back by referring to the original dictionary (JSONDictionary) the item has gone.
I understand this is expected. If Dictionary1 = Dictionary2, a new dictionary is not actually created. Only an second address. So if you change Dictionary1, Dictionary2 also changes.
A practical example could be setting a price range. You can reduce the range and have less items displayed on the table. But you can't replace previously deleted items if you wanted to increase the price range. I do not want to recall the JSON script each time I edit the range. Advice appreciated.
As confirmed by the OP, ItemModel is a class and not a Dictionary. To fix this you need to make ItemModel a real Dictionary and thus a value type. This is probably the preferred choice but will be more work.
An alternative would be to add an convenience initializer to the ItemModel class that instantiates a new copy of itself and call that instead of setting self.ItemDictionary = self.JSONDictionary.
Something like this.
init(model: ItemDictionary) -> ItemDictionary {
// copy properties
}
Then create the new copy.
self.ItemDictionary = ItemDictionary(self.JSONDictionary)
Later you can reinitialize ItemDictionary with the same call.
Try this code out-
var dictionary1 = ["name": "Magnus"]
var dictionary2 = dictionary1
dictionary2.removeAll()
print("\(dictionary2) \(dictionary1)")
The output is :-
[:] ["name": "Magnus"]
Thus 2 new dictionaries are being created. If you refer to the Swift documentation, You will find that in swift, references are hardly present.
Some other portion of code might be responsible. Hope this helps :-)

How to pass json data in swift app between two viewcontrollers

I need help with passing json data.I have json data in this array
var TableData:Array< String > = Array < String >()
In this Array I have Name,Address,Latitude, Longitude
I show Name and Address in a tableView , but I would like to create annotation in different viewController with Latitude and Longitude depending on which cell user taps(Name,Adress,latitude,Longitude shoulld be equal) , so I am asking you if there is some good tutorial in swift , or if you have just some advice.
Thank you.
There are many different ways to pass data from one swift file to another. In the case that there is a rootViewController and a button is clicked to open a new ViewController. Having previously defined an array in the new ViewController, the json parsed array can be passed along using the prepareForSegue method.
Another popular way to pass information between different swift files would be using the AppDelegate. Here you can create instances of different swift classes using a method known as instantiateViewControllerWithIdentifier("identifier"). This can be done by creating a storyboard variable then calling this method by doing storyboard.instantiateViewControllerWithIdentifier("identifier").
let newvc = self.storyboard?.instantiateViewControllerWithIdentifier("newvcIdentifier") as! (UIViewController extended class)
newvc.data = TableData
self.navigationController?.pushViewController(newController, animated: true)
where newvc has a variable declared as follows:
var data: Array <String>!
Another method that can be used is having shared data among all of the classes using a singleton. A singleton can be created very simply in swift3, take a look here for details.
class JSONData {
var json: Array <String>
static let sharedInstance = JSONData()
}
Before segueing to the next vc, you should store the data in the sharedInstance class. This should be done by overriding the prepare method. Documentation on this method can be found here
sharedInstance.json = self.json
Once the data is set in the shared instance, after the new view controller is loaded, this data can be accessed through sharedInstance.json.
Hope this works for you and just comment if you have any other questions!
I would do something like this:
let newController = self.storyboard?.instantiateViewControllerWithIdentifier("newControllerIdentifier") as! NewControllerClassName
newController.data = array
self.navigationController?.pushViewController(newController, animated: true)
It also appears you are using a array of string type that are comma separated.
I would rather create a variable like below
var jsonArray:[[String:String]]?
so I am asking you if there is some good tutorial in swift
http://matteomanferdini.com/how-ios-view-controllers-communicate-with-each-other/
He covers clean code and best practices. Better read this before implementing anything.
or if you have just some advice
Your code needs to be clean. Passing latitude as String it's going to create you a problem later (conversions, code understanding, or even bugs).
Make a new account here and watch uncle Bob. His lessons are valuable. matteomanferdini above follow uncle bob practices.
https://www.safaribooksonline.com/library/view/clean-code/9780134661742/

Array spontaneously emptying

I'm currently working on an app, and for some reason an array is spontaneously emptying.
I first mention it at the top of the file:
let scaleTypes = [String]()
I then populate it (I verify it's populated by running a println of the array):
let scaleTypes = scaleTypesDict.valueForKey("Types")! as! [String]
println(scaleTypes.count)
When I access the array (when populating the contents of UITableViewCells):
cell.textLabel!.text = scaleTypes[indexPath.row]
I get fatal error: Array index out of range. I've done a println of the array count directly before I access the array, and found that it's emptied itself (it prints 0). The array is not mentioned elsewhere in the file. I use a similar variable name in another view controller in this app, but I highly doubt that that is causing the issue. Anyone got anything?
EDIT: If viewing the entire source code would help, it can be found here: https://gitlab.carson-greene.com/cgreene/scales-ios/tree/dev/Scale%20Randomizer. Unfortunately, I haven't commented things well; be warned. The file that this error happens in is the SRSettingsViewController.swift file.
You are declaring two different variables called scaleTypes.
The first is a member variable, which since you declare with let and then initialize to be empty, will never contain anything.
Then, in your viewDidLoad you are declaring a new, local variable called scaleTypes. You put values in it, but it only exists while your viewDidLoad function is running, where it masks the member variable. When that function exits, it disappears.
Elsewhere in other functions, when you access scaleTypes, you are accessing that empty member variable.
If instead you declare your member variable with var, and then drop the let in front of the assignment in viewDidLoad, you’ll assign the values to the member variable as you’re hoping.
The second time you write let scaleTypes, you are declaring a new array, local to the method it's in.
Change your first let to var, and then append the values later instead of making a new array.
Also, you shouldn't use valueForKey(). Just use the keyed subscripts:
// Declare the variable as mutable
var scaleTypes = [String]()
// Later, add new variables…
if let newScales = scaleTypesDict["Types"] as? [String] {
scaleTypes += newScales
}
Remove the let before populating the array, you're creating a local scoped array with the same name

Resources