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]()
Related
Can anyone teach me how to initiate/add items in array as section?
something like - array[["john"],["daniel"],["jane"]]
tried a few like var d = ArrayList<CustomClass>(arrayListOf<CustomClass>())
that does not work.
for example, if i add "david" i want it look like array[["john"],["daniel", "david"],[“keith"]] by finding the index of array contains letter "d"
how can i display them on a custom base adapter / listview? currently using a viewHolder
val viewHolder = ViewHolder(row.name) to display.
Thanks!
If I am right, you're trying to create an ArrayList that contains other ArrayLists. So writing:
var d = ArrayList<CustomClass>(arrayListOf<CustomClass>())
Won't work because the type of the main ArrayList is not String, but ArrayList. So you need to write:
var names = ArrayList<ArrayList<String>>()
names.add(arrayListOf("jane", "john))
Regarding the second question, check out this course that has a section about RecyclerView: https://classroom.udacity.com/courses/ud9012 If you are a beginner, I strongly encourage you to follow the whole tutorial.
Please forgive my terminology, Im not educated on the proper.
Lets say I have multiple movieclip variables
var rblock1:MovieClip = new Rblock();
var rblock2:MovieClip = new Rblock();
var rblock3:MovieClip = new Rblock();
var yblock1:MovieClip = new Yblock();
var yblock2:MovieClip = new Yblock();
var yblock3:MovieClip = new Yblock();
I have them added to an array
var blockarray:Array = new Array(rblock1, rblock2, rblock3, yblock1, yblock2, yblock3);
var block
I want to create a for loop with an if statement that triggers if a variable is Rblock and not Yblock, for example
for each (block in blockarray)
{
if (block==Rblock)
{
trace("rblock");
}
}
The issue is that obviously "if (block==Rblock)" doesnt work.
How should this be written?
You apparently want to check if a block is red or yellow by checking against its class name. You can do it with this:
if (block is Rblock) {...} // yes, red
I have figured out a work around not really a perfect solution, which will only work for certain scenarios...
if each class has a unique trait you can identify it that way, for example...
if all variables defined by the Rblock class are wider than the Yblock class you could say
if (block.width>x) { trace(Rblock); }
Like I said this is only a work around though and only works for movieclip variables defined by classes that are different, if anyone has the actual solution please post
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.
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
I have an array named arr of type [Int8]:
var arr: [Int8] = []
Throughout the program I add items to the array using append and insert. However, when I try to remove an item using arr.removeIndexAt(x), it throws the error:
Playground execution failed: <EXPR>:144:13: error: immutable value of type '[Int8]'
only has mutating members named 'removeAtIndex'
arr.removeAtIndex(x)
Why is this happening? I tried recreating this in a playground:
var arr: [Int8] = []
arr.append(1)
arr.removeAtIndex(0)
and it works fine. Could someone please explain to me how I might fix this problem or remove an item another way? Any help wold be great. Thanks :)
Found the solution. Add mutating to your definition of removeExtraZeros() to allow it to alter properties, i.e,
mutating func removeExtraZeros() { ... }
Unfortunately you run into an issue where the while loop after that for loop is looping infinitely, so consider revising that part as well.
You say when you try to remove an item using arr.removeIndexAt(x), it throws the error.
Because the method name is removeAtIndex:, not removeIndexAt: