Referencing a Struct not using the variable's name - arrays

Hello I have a swift file that contains arrays of tuples that I reference with my app. For example, my structure looks like:
struct workoutDict {
static var bicepWorkouts = [("Barbell Curl","Bicep",0,"3x10"), ("x","x",3,"x")]
}
I have a global variable named eqID. For example, eqID = "bicepWorkouts"
There is part of my code where I attempt to call this dictionary. Normally I would use: workoutDict.bicepWorkouts and this works fine, but I have other workouts such as barbellWorkouts in my dictionary so i let the user select "bicepWorkouts", "barbellWorkouts" ect based on user input and need to use that to reference my struct.
Right now i have
//Call the global variable to get what workout to look for
code = eqID
let ourWorkouts = workoutDict.code
which should set ourWorkouts = workoutDict.bicepWorkouts when our eqID is set to that, but it keeps giving me the error that workoutDict does not contain the code when I use that reference.
I tried researching alternate methods of referencing structs but I couldn't find anything. Any help would be appreciated!

You should create yet another dictionary to store the names:
struct workoutDict {
static var dicts = [ "bicepWorkouts": bicepWorkouts, "barbellWorkouts": barbellWorkouts ]
}
Then you can access the sub dictionaries by:
workoutDict.dicts[eqlID]

Related

Iterate through an array in an array of dictionaries swift

I am currently in a bit of a bind.
struct sectionWithDatesAsName {
var sectionName : String
var sectionObjects : [SoloTransactionModel]!
init(uniqueSectionName: String?, sectionObject: [SoloTransactionModel]?) {
sectionName = uniqueSectionName ?? "nil"
if let section = sectionObject {
sectionObjects = section.reversed()
}
}
}
I currently have an array of sectionWithDatesAsName. And I can work with it, display in the tableView among other things.
The bind comes up when I want to check some information in the sectionObject before displaying it on the tableView.
I want to check the type of the sectionObject which is saved in the object itself.
How do I check the information in the sectionObject without slowing down the app? Or have a horrible time complexity calculated?
(Note: I can't change the format of the struct has this has already been used by a whole lot of other processes)
Write a function in your sectionWithDatesAsName with the signature filteredSections(type: sectionType) -> sectionWithDatesAsName
(If you don't have the ability to edit the definition of sectionWithDatesAsName you can create an extension that adds the above function)
If the sectionWithDatesAsName is defined elsewhere, define this function in an extension.
When you call it, build a new sectionWithDatesAsName object by filtering the arrays to match the specified type.
Use the resulting filtered sectionWithDatesAsName object as the data model for your table view. It will be built once and used for the lifetime of the tableView, so you will pay an O(n) time cost to filter it once when you create it.

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.

How would you create a multidimensional array with n dimensions in Swift?

For instance, asume
var hierarchicalFileSystem: [[String]] = []
This allows one to support one layer of folders, but there appears to be no way to create an array in Swift like the one above but with an undefined number of nested String arrays.
Am I missing something here?
An array of arrays (of arrays of arrays...) of strings doesn't really make much sense to represent a file system.
What I'd instead recommend is making a class or struct to represent objects in the file system. Perhaps something like this:
struct FileSystemObject {
let name: String
let extension: String?
let isFolder: Bool
let contents: [FileSystemObject]?
}
Something like this let's us represent a file system quite nicely.
let fileSystem = [FileSystemObject]()
So, your fileSystem variable here is an array of FileSystemObjects and it represents the root. Each object within the root has its own set of details (its name, its file extension if it has one, and whether or not its a folder), and if it's a folder it has a non-nil contents property, and if it's a non-empty folder, that contents array of FileSystemObjects contains more file system objects (some of which are folders of course, which contain contents themselves).
What you can perhaps do is create an array with AnyObject and add new depths as you need it
var fileSystem: [AnyObject] = []
This would be a very bad way of representing a file system however and you should really go with some kind of tree structure like
struct Node {
children: [Node]?
parent: Node?
name: String
}
Swift is type-safe language. You have to declare type of your variable, or set it to AnyObject, but please don't. So, answering your question: yes it's possible:
var array: [AnyObject] = [[[1,2,3], [1,2,3]], [[1,2,3],[1,2,3]]]
But this is awful. Try to figure out better representation for your problem. Maybe custom structures.
you can have as much dimensional array as you want. is it a good idea? i don't think ...
var threeDArray: Array<Array<Array<String>>> = []
let oneDArray = ["1","2","3"]
let twoDArray1: Array<Array<String>> = [oneDArray, oneDArray, oneDArray, oneDArray, oneDArray]
let twoDArray2 = twoDArray1 + [["4","5","6"],["7","8","9"]]
threeDArray.append(twoDArray1)
threeDArray.append(twoDArray2)
let arr = [threeDArray,threeDArray,threeDArray]
print(arr.dynamicType) // Array<Array<Array<Array<String>>>>

Code Igniter: Access array elements from controller

I have written this function in CI and for various reasons, I need to assign the contents of the array to variables to use later in the controller.
Because of the way this legacy code is set up, I need to get to the elements of the array from the controller. How do I get to the array elements in $data['oneResult'] from function below. I have tried a few things like the element() helper. Nothing works. In debug mode, I see the data I need and at this point, I need to assign so I want to do this:
$holdID = $data['oneResult']['contact_id'];
$holdLoc = $data['oneResult']['location']; etc.
public function getOneValue(){
$this->load->model('get_contents');
$data['oneResult'] = $this->get_contents->getSpecificRow();
$data['title'] = 'One Record - Contacts table view';
$this->load->view('contacts_view', $data);
}
I am testing this in CI 2, but will need it to work in CI 1.7
Can anyone show me how to do this please?
make a global variablw and assign the data to it..
class something extend CI_controller{
var $holdID ='';
var $holdLoc = ''; etc.
public function __construct() {
....
}
public function index(){
...
}
public function getOneValue(){
$this->load->model('get_contents');
$data['oneResult'] = $this->get_contents->getSpecificRow();
$this->holdID = $data['oneResult']['contact_id']; //<----here assing value to global var
$this->holdLoc = $data['oneResult']['location']; //<--here
$data['title'] = 'One Record - Contacts table view';
$this->load->view('contacts_view', $data);
}
}
I suppose you want the data to be available the next time you are visiting the controller.
In that case, global variables won't hold the value because of the architecture and functioning of codeigniter.
Here are possible ways, that i can suggest:
1) declare session variables and use.(not a very efficient one)
2) declare variable in config file.(preferred and might just do the trick for you).
If either of the above two does not resolve your issue, elaborate a little on your use-case.
Will give it a fresh attempt.
-- seekers01

Accessing instance properties inside of an array

I've imported several images into an actionScript 3 document. I've turned them all into symbols (movie clips) and given them instance names to reference from ActionScript.
Ok, so I'm putting the instances into an array so I can loop through them easily, but for some reason, whenever I'm putting in the instance name, I do a trace on the value in the array and it's giving me the symbol object back, rather than the instance object.
Basically trying to loop through the array to make each instance's visibility = false
Here's a sample:
var large_cap_extrusion_data: Array = new Array();
large_cap_extrusion_data[0] = large_cap_extrusion_menu_button;
large_cap_extrusion_data[1] = extrusion_border_large_cap
large_cap_extrusion_data[2] = "Large Cap";
large_cap_extrusion_data[3] = large_cap_main_menu_button;
var extrusion_data: Array = new Array();
extrusion_data[0] = large_cap_extrusion_data;
trace(extrusion_data[0][0]);
The traces gives:
[object large_cap_menu_button]
(the parent symbol)
rather than:
"large_cap_extrusion_menu_button"
I'd be very grateful if someone could tell me where I'm going wrong...
when you trace and object, by default it describes it type. What you want is the "name" property of the object.
Try this:
trace(extrusion_data[0][0].name);
that should give you the instance nema of the large_cap_menu_button rather than the class description. Either way, you have the right object I bet.

Resources