I am learning how to build apps and working with Swift for this project.
I had a buddy help me pull data in from a website and it looks like he created classes with variables and mapped them to certain extensions (IE "Username") so when I call the variable data such as profile I would call it. The below uses luck_30 able to store "Stats.luck_30"
luck_30.text = profile.luck_30
So inside one of my variables that is in this "Profile" class is setup into an array. I can pull the array out of the class, but I can't seem to do for while statement replacing the [#] with a variable from the for command.
func aliveWorkers(profile: Profile) -> NSNumber{
var myworkers : Array = profile.workers!
//this test works and returns the proper value
var testworker: NSNumber = myworkers[0].alive!
println("The satus of the test worker is " + testworker.description)
/* This code is giving error "Could not find member alive" it does not ifor var
for ifor in myworkers{
var thisworker: NSNumber = myworkers[ifor].alive! as NSNumber
}
*/
return 42
}
Your variable ifor is not a counter, it is an actual object. You could do something like this:
for worker in myWorkers {
let workerIsAlive = worker.alive!
}
Alternatively, if you need the index,
for i in 0 ..< myWorkers.count {
let worker = myWorkers[i]
let workerIsAlive = worker.alive!
}
If you need both:
for (i, worker) in enumerate(myWorkers) {
let workerIsAlive = worker.alive!
}
And as a matter of style, I would stay away from NSNumber and use Int or Bool or whatever the data actually is. Also, it looks like the alive variable should not be optional, as you're unwrapping it everywhere. To avoid "mysterious" crashes later, you may want to think about making it a non-optional type.
when using a for in loop, your loop variable isn't an index, its the objects you're looping through. so..
func aliveWorkers() {
var myworkers = [1, 2, 3]
//this test works and returns the proper value
let testworker = myworkers[0]
print("The satus of the test worker is \(testworker)")
for ifor in myworkers {
print(ifor)
}
}
Notice a few things... you don't need to use + to concatenate those strings. you can just use string interpolation. \(variable) inserts the value of variable in the string.
Try to use let instead of var when you don't change the variable. You don't need to explicitly define type on variables either.
Related
I have a computed array which is full of tags and updates depending on what selection i make in the select box. I would like to take this array and pass it to a method and then run a method to update what “results” have an active class. Although I get an array saying I can’t run forEach on this element.
Been through a few topics and understand computed properties dont work like that but surely there is a way around this.
https://jsfiddle.net/39jb3fzw/6/
Short Snippet
methods: {
updateOutput() {
var tags = this.tagArray;
tags.forEach(function(tag) {
console.log(tag);
})
}
},
computed: {
concatenated: function () {
var ret = this.selected.concat(this.selected2, this.selected3);
this.tagArray = ret;
//this.updateOutput();
return ret;
}
}
Full Output
https://jsfiddle.net/39jb3fzw/6/
Thanks again :slight_smile:
It looks like the issue is the line:
var ret = this.selected.concat(this.selected2, this.selected3);
That line of code is returning an empty string rather than an array. This is because this.selectedX is a string rather than an Array. This explains why tag.forEach is undefined. forEach doesn't exist on the String prototype.
You can create this an array instead be doing
var ret = [ this.selected, this.selected2, this.selected3 ]
From there you can set this.tagArray to ret
Hope this helps
I have many class in my library almost 300, and I want to generate instance name by loop. In other words I wanna instead of this approach(witch has many code line):
X:This is my problem:
var cm1: Cm1 = new Cm1();
var cm2: Cm2 = new Cm2();
var cm3: Cm3 = new Cm3();
...
use like this approach (less than 10 code lines):
Y:I think this is solution:
for (var i: uint = 1; i < 4; i++)
{
var getChildByName("cm" + i): getChildByName("Cm" + i) = new getChildByName("Cm" + i);
}
but I know above code does not work, is there any way to make them !
-What am I actually trying to solve?
Make many variable by a few line code and save time and size app!
-Why do I have ~300 classes and why are you trying to create them in a loop at once?
This is about to data of request application!
-What do these classes do that you unconditionally need one of each all at the same time?
Because those data would show at first time!
First, it is better to store the classes in an Array or Object rather than an external variable for each item. if you want to access them by name, better to use object:
var classList:Object=new Object();
Then in your loop:
for(var i:uint=1;i<NumberOfClasses;i++){
classList["cm"+i.toString()]=new (getDefinitionByName("Cm"+i.toString()) as Class)();
}
getDefinitionByName is used to make Constructors using String;
Note: if your classes contain a package directory, you should include it. for example:
getDefinitionByName("myclasses.cm.Cm123")();
Then you can access them using Bracket syntax:
classList["cm123"].prop=val;
And don't forget to:
import flash.utils.getDefinitionByName;
I Hope it will help.
EDIT
to use Array instead of object, the loop should be:
for(var i:uint=1;i<NumberOfClasses;i++){
classList[i]=new (getDefinitionByName("Cm"+i.toString()) as Class)();
}
then to access them:
addChild(classList[0]);//0 or any other index;
I am currently learning swift and am experimenting with data structures. In may code I have certain routines with a name(String) and several tasks(Array of Strings). These values are in a structure.
So I am trying to add another value to the array after it has been initialized. My code is actually working, however I really think it very weird and odd and DO NOT think, that it is the way it should be done.
var routineMgr: routineManager = routineManager();
struct routine{
var name = "Name";
var tasks = [String]();
}
class routineManager: NSObject {
var routines = [routine]();
func addTask(name: String, desc: String){
//init routines with name and an array with certain values, here "Hallo" & "Moin"
routines.append(routine(name: name, tasks: ["Hallo","Moin"]));
//so i just put this part here to make the example shorter, but it would be in ad different function to make more sense
//adding a new value ("Salut") to the tasks array in the first routine
//getting current array
var tempArray = routines[0].tasks;
//appending new value to current value
tempArray.append("Salut");
//replacing old routine with a copy (same name), but the new array (with the appended salut)
routines[0] = routine(name: routines[0].name, tasks: tempArray);
}
}
I have tried some (to me) "more correct" ways, like:
routines[0].tasks.append("Salut");
But I always got tons of errors, which I also did not understand.
So my question now: How is it actually done correctly? And why does the second way not work?
Your help and advice is really appreciated!
You can create a function to append the values in the struct (that is what I would do). You can even use it to validade values or anything else you need to do before append, it can also return a boolean to let your code know if the value was successfully appended or not
var routineMgr: routineManager = routineManager();
struct routine{
var name = "Name";
var tasks = [String]();
mutating func addTask(task: String){
tasks.append(task)
}
}
class routineManager: NSObject {
var routines = [routine]();
func addTask(name: String, desc: String){
routines.append(routine(name: name, tasks: ["Hallo","Moin"]));
routines[0].addTask("Salut")
}
}
I hope that helps
i use the following function to retrieve a random person from an array:
func getRandomPerson() -> String{
if(personArray.isEmpty){
return ""
} else {
var tempArray: [String] = []
for person in personArray{
tempArray += [person.getName()]
}
var unsignedArrayCount = UInt32(tempArray.count)
var unsignedRandomNumber = arc4random_uniform(unsignedArrayCount)
var randomNumber = Int(unsignedRandomNumber)
if tempArray.isEmpty {
return ""
} else {
return tempArray[randomNumber]
}
}
}
I would like to use this function inside an array of strings, Like this:
var theDares: [String] = ["Dare1 \(getRandomPerson())", "Dare2", "Dare3", "Dare4", "Dare5"]
But when i use the functions, it only runs the function once. Can you make the function run everytime you use the "Dare1" in this instance.
Thanks in advance
I think you are asking if you can set up your array so every time you fetch the object at index 0, it re-builds the value there.
The short answer is no. Your code is creating an array of strings, and the item at index 0 is built ONCE using a function call.
However, it is possible to make a custom class implement the subscript operator. You could create a custom object that looks like an array and allows you to index into it using an Int index. In response to the index operator you could run custom code that built and returned a random string.
Since it sounds like you're a beginning programmer creating a custom class the implements the subscript operator might be beyond your current abilities however.
Try like this:
let personArray = ["John", "Steve", "Tim"]
var randomPerson: String {
return personArray.isEmpty ? "" : personArray[Int(arc4random_uniform(UInt32(personArray.count)))]
}
println(randomPerson) // "Steve"
Using getDefinitionByName I am consistently getting the error saying it is not defined (as the title says). The particular code I am using is
var tileID:String = String(getDefinitionByName("evt.target.data."+mapData[i][j]))
mapData is already populated by a character in each position. The plan is that I can use the value of whatever mapData is as the variable name for the conversion of the single character to the full linkage name of a tile. These properties come from another external .txt file that is setup for variables (this is the external file the code line links to).
The variables in the external file look something like &N=exampleTile.
So when it comes to setting tileID it should end up being exampleTile. (Assuming mapData[i][j] = "N").
But it doesn't. I have read around at other solutions saying that the file may not have loaded or anything, but I can't make sense of or apply any of those fixes.
As Florian points out, getDefinitionByName is specifically for getting a Class reference. Something like "flash.net.URLLoader" would give you a reference to the URLLoader class for example. It's not used for getting regular variables by their names (so "evt.target.data.N" wouldn't return anything even if "N" was a property of data).
It sounds like your evt.target.data is a long string along the lines of "A=tileA&B=tileB&C=tileC". If so, you need to parse that string out to separate variables first. You should be able to use URLVariables with that data format (flash.net.URLVariables), then you can read the parsed variables using the [ ] array access operator: urlVariablesObject["variableName"]. So you might do something like this:
import flash.events.Event;
import flash.net.URLVariables;
import flash.net.URLLoader;
import flash.net.URLRequest;
var loader:URLLoader = new URLLoader();
var parsedData:URLVariables;
var mapData:Array = [["A", "B", "C"], ["D", "E", "F"]];
loader.addEventListener(Event.COMPLETE, externalFileLoaded);
loader.load(new URLRequest("externalFile.txt"));
// externalFile.txt contains "A=tileA&B=tileB&C=tileC&D=tileD&E=tileE&F=tileF".
function externalFileLoaded(evt:Event):void {
parsedData = new URLVariables(evt.target.data);
var tileID:String = readMap(0, 1);
trace(tileID); // "tileB".
}
function readMap(i:uint, j:uint):String {
var mapValue:String = mapData[i] [j];
var tileID:String = parsedData[mapValue];
return tileID;
}
That doesn't make any sense. getDefinitionByName is used to retrieve a Class instance of a certain type - the Class named like the string passed. And the definition will always start with "evt.target.data.".
Did you ever debugged your way through it?
function any_handler(i:int, j:int):void {
const suffix:String = mapData[i][j],
qualifiedName:String = "evt.target.data." + suffix;
// this is wrong
const titleID:String = String(getDefinitionByName(qualifiedName));
}
You really should take a look in the debugger in order to know the value of the string you are creating.