Xcode Swift - How to initialize a 2D array of [[AnyObject]] of as many elements you want - ios

I know I can initialize an array of Ints for example like:
var intArray = [Int](count: 10, repeatedValue: 0)
What I want to do is something like this:
var array = Array(count:6, repeatedValue:Array(count:0, repeatedValue:AnyObject()))
(Xcode returns with: AnyObject cannot be constructed because it has no accessible initializers)
With the same outcome as I could initialize the array like:
var anyObjectArray : [[AnyObject]] = [[],[],[],[],[],[]]
But doing the above is ugly if i need like 100 rows of lets say 3
The problem is I can append in my function like:
// init array
var anyObjectArray : [[AnyObject]] = [[],[],[]]
//inside a for loop
anyObjectArray[i].append(someValue)
That works ok, until of course i gets higher then the number of rows in the array.
A answer to this problem is also acceptable if I could do something like:
anyObjectArray[append a empty row here][]
But that is probably stupid :)
I hope there is a way to do this cause I don't feel like having a line like:
var anyObjectArray : [[AnyObject]] = [ [],[],[],[],[],[],[],[],[],[],[],[],[],[],[], ... etc ]
at the top of my page ;)
Thank you for your time!

You don't need the second repeatedValue initialiser, since you want an empty array. You can just use
var array = Array(count:6, repeatedValue:[AnyObject]())

You can try with 2 loops, working as a grid :
var items: = Array<Array<Item>>()
for col in 0..<maxCol {
var colItems = Array<Item>()
for row in 0..<maxRow {
colItems.append(Item())
}
items.append(colItems)
}
//Append as much as you want after

Try this
let columns = 27
let rows = 52
var array = Array<Array<Double>>()
for column in 0... columns {
array.append(Array(count:rows, repeatedValue:Int()))
}

Try using this
let array = Array(count:6, repeatedValue:[])
for (var i=0; i<array.count; i++){
array[i] = Array(count:0, repeatedValue: AnyObject.self)
}
in place of your code.

Swift 3:
var array = Array(repeating:[AnyObject](),count:6)

Related

How to append an array to an array at current index?

I have an array myarray and I am using a for loop to get a few information which I add to myarray. But next time the for-loop runs, I don't want to create a separate index, but instead the 2nd time and so on, I want to append the information to myarray[0].
How do I do that?
var myarray = [String]()
for var j in 0 < 12 {
// do some stuff
for var i in 0 ..< 10 {
let parta = json?["users"][j]["name"].string
let partb = json?["users"][j]["Lname"].string
let partc = json?["users"][j]["dob"].string
myarray.append("\(parta)-\(partb)-\(partc)---")
// Here when the for loop comes back again (i = 1) , i dont want to make
// myarray[1] , but instead i want myarray[0] ,
// having value like [parta-partb-partc--parta-partb-partc]
}
}
Basically what I am trying to do is, append the new name/lname/dob values at myarray[0] without affecting the current value/string at myarray[0].
You can insert single element and also add array as below.
Swift 5
var myarray = [String]()
myarray.insert("NewElement", at: 0)
myarray.insert(contentsOf: ["First", "Second", "Third"], at: 0)
If I understand your question correctly, you want to create one long string and add the new data always at the beginning of the string. One way to do that would be:
// Store somewhere
var myString = String()
for var i in(0..<10) {
let parta = json?["name"].string
let partb = json?["Lname"].string
let partc = json?["dob"].string
let newString = "\(parta)-\(partb)-\(partc)---")
newString.append(myString)
myString = newString
// Here when the for loop comes back again (i = 1) , i dont want to make
//myarray[1] , but instead i want myarray[0] ,
//having value like [parta-partb-partc--parta-partb-partc]
}

how to store values in a 1D array into a 2D array in Swift 4

Hi I would like to store values of a 1D array into a 2D array.
My 1D array has 50 elements and I want to store it in a 5x10 array, but whenever I do that, it always gives me a "Index out of range" error
Any help would be appreciated thanks!
var info2d = [[String]]()
var dataArray = outputdata.components(separatedBy: ";")
for j in 0...10 {
for i in 0...5 {
info2d[i][j] = dataArray[(j)*5+i]
print(info2d[i][j])
}
}
Lots of error in your code.
info2d must be initialised with default values before using it by index
// initialising 2d array with empty string value
var info2d = [[String]](repeating: [String](repeating: "", count: 10), count: 5)
Secondly for loop with ... includes the last value too, use ..<
for j in 0..<10 {
//...
}
Thirdly (j)*5+i is incorrect too.
Better Read how to use arrays, collections and for loop in swift.
https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html
https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html
I would make use of ArraySlice for this.
var arr2D = [[String]]()
for i in 0..<5 {
let start = i * 10
let end = start + 10
let slice = dataArray[start..<end] //Create an ArraySlice
arr2D.append(Array(slice)) //Create new Array from ArraySlice
}

Filter an array of objects by an array of dictionaries contained in the object

So I need to filter an array of objects by an array contained in the object
the object looks like this
class thing {
let list = [stuff, stuff, stuff, stuff]
}
class stuff {
var name = "ugly"
}
The array looks like this
thingArray = [thing, thing, thing, thing]
and my code so far looks like this
newArray = thingArray.filter { receipt in
return thing.thingArray.lowercaseString.containsString(searchText.lowercaseString)
}
So my problem is that I can't get this function to work and what I really need is a way to filter this array of objects by the array contained inside of the object. Any help is definitely appreciated.
p.s. I just tried this to no avail:
test = thingArray.filter {$0.list.filter {$0.name.lowercaseString.containsString(searchText.lowercaseString) == true}}
If I understood correctly, your problem can be solved with something like this:
class thing {
init(list: [String]) {
self.list = list
}
var list: [String]
}
let thingArray = [thing(list: ["one", "two", "three"]), thing(list: ["uno", "due", "tre"]), thing(list: ["uno", "dos", "tres"])]
let searchString = "uno"
let result = thingArray.filter {
$0.list.contains(searchString)
}
//it will print "uno", "due", "tre"
result.first?.list

How to add elements to an array of custom objects in Swift

I am using this code to add custom objects to an array and then display that data in a custom TableView.
var tempCount = self.people?.count
for var k = 0 ; k < tempCount ; k++
{
if let PERSON = self.people?[k]
{
let name = (PERSON.compositeName != nil) ? PERSON.compositeName : ""
let number = (PERSON.phoneNumbers?.first?.value != nil) ? PERSON.phoneNumbers?.first?.value : ""
let image = (PERSON.image != nil) ? PERSON.image : UIImage(named: "aks.jpg")
let details = Contact(userImage: image!, userName: name!, phoneNumber: number!)
println(details.userName + " " + details.phoneNumber)
self.arrayOfContacts?.append(details)
println(self.arrayOfContacts?.count)
}
}
The count of the elements in the array always seems to be 'nil' for some reason. I have declared the array in the following manner
var arrayOfContacts:[Contact]?
, Contact being the type of Object that array is supposed to contain.
and the other one as
var people : [SwiftAddressBookPerson]? = []
The print statement does give out results but the object never gets added into the array.
Any idea about what I am doing wrong would be greatly helpful.
Your array is declared as an Optional array but is not created so it's nil.
Your declaration:
var arrayOfContacts:[Contact]?
Add the creation of an actual empty array:
arrayOfContacts = []
Or create it at once altogether:
var arrayOfContacts:[Contact]? = []
Your arrayOfContacts is nil, so arrayOfContacts?.count is nil as well.
If you really want to append to arrayOfContacts, don't write self.arrayOfContacts?.append(details) because this means "append to arrayOfContacts but actually I don't really care and if arrayOfContacts is nil, just give up".
Instead, write self.arrayOfContacts!.append(details), because now this means "append to arrayOfContacts, and since I really do care, tell me hard and loud, with a fatal crashing error, when arrayOfContacts is nil because well I'll have to figure out why on hell this array is nil when it should not be. I mean, I'm the master of the machine, not the opposite, and I know quite well that arrayOfContacts ought to be not nil when I want to append to it."
Often when you’re dealing with data you don’t just have a fixed amount of elements. Take for example a program where you compute the average of multiple grades in a class:
var grade1 = 4
var grade2 = 3
var average = Double(grade1 + grade2) / 2.0
println("Average grade: \(average)")
What if we wanted the program to also work when we have 3 grades?
We’d have to change our program to work with 3 grades.
var grade1 = 4
var grade2 = 3
var grade3 = 5
var average = Double(grade1 + grade2 + grade3) / 3.0
println("Average grade: \(average\)")

Swift Fill sections & rows in UiTableview

I am trying to fill in a table view from a dictionary data source and tried a lot to achieve desired result but lot of error, need help on this:
this is my test code in playground which almost gives me desired result, but when i try to do same thing in project nothing works:
I have marked my questions next to problem command line:
var sections = Dictionary<String, Array<String>>()
var mySId = ["s1","s2"]
var m``Sdate = ["jun1", "jun2"]
var mEdate = ["jun2", "jun4"]
var mytotalArr = [String]()
var index = 0
for myId in myScId {
mytotalArr.append(mSdate[index]) // transfer data to total array to group
mytotalArr.append(mEdate[index]) // tarnsfer data to total array to group
sections["\(myScId[index])"] = mytotalArr
index++
}
println(sections["sch1"]!) // "[jun1, jun1]"
// in project i do it like this
in cellForRowAtIndexPath
var myarr = sections[indexpath.section]
when i do same as above in project error message // Unresolved Identified indexPath
var mystring = sections["sch1"]!
println(mystring[1]) // "jun1"
Or Please suggest a way to achieve the result as below
Section header = Sch1 ,
row1 = jun1 // mSdate ,
row2 = jun2 // mEdate
section header = Sch2 ,
row1 = jun2 ,
row2 = jun4
Solution for this was not simple to figure out, but i managed using other Stack's.
Basically first you get the value from your first key in Dict, and that search for data witihin it.
little overkill on system and coding, but it works.

Resources