i have variable of type [Int: [CustomObject]], and i need to count [CustomObject].count by key in my numberOfRowsInSection ? how can i access this value ?
var tasks = [Int :[TaskEntity]]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("section: \(section), taskKey: \(tasks.keys.sorted())")
}
Like each key in dict has an array of elements as value, i need to count this elements in array for each key-value pair
UPD: I'he added print line as Joakim Danielson suggested. Print says:
When i add cell to section 0: "section: 0, taskKey: []
section: 0, taskKey: [0]"
When i add cell to section 1: "section: 1, taskKey: [0, 1]
section: 0, taskKey: [0, 1]"
Now i'm confused about output
Related
I've got an NSComboBox in my app, and I'd like it to display the contents of an array per line from a multi-dimensional array, rather than an element from a one-dimensional array.
My ViewController conforms to NSComboBoxDataSource, has the two required methods (numberOfItems and objectValueForItemAt index), and within viewDidLoad() I've set:
myComboBox.usesDataSource = true
myComboBox.dataSource = self
Everything works perfectly with a one-dimensional array.
I've got the following array:
var testArray: [[String]] = [["Array 1", "Element"],["Array 2", "Element"]]
followed by the following functions later on:
func numberOfItems(in comboBox: NSComboBox) -> Int {
return testArray.count
}
func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
return testArray[index]
}
Please see the attached screengrab for what my NSComboBox returns (which is just '(' on each line). I had expected the first line to return ["Array 1", "Element"] and the second line to return ["Array 2", "Element"]. Ideally I'd want the NSComboBox to return only the contents of the arrays like so: Array 1, Element (i.e. without [ ] and ")
The closest I've got is by trimming characters as follows:
func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
return String(describing: testArray[index]).trimmingCharacters(in: CharacterSet(charactersIn: "[]\""))
}
But that returns Array 1", "Element, so if anyone has any suggestions for why it hasn't trimmed all the \" that would be appreciated too.
I'm new to Swift so apologies if I've missed something obvious!
Thanks in advance.
If you want to control the String representation, you should better not modify the output of String.init(describing:).
And trimmingCharacters(in:) trims the both ends of a String.
Try something like this:
func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
return testArray[index].joined(separator: ", ")
}
I am creating an iOS Swift 3 app and in this app I have a tableview with data coming from an API. I want to display this data in the tableview but I want to do it grouped by firstname. I have managed to first group the data (see below) but xCode is complaining that XXX.
This is the declaration of the sections:
var sections = [String: [User]]()
This is how I group the data:
self.sections = Dictionary(grouping: self.contacts.filter({ !$0.firstname!.isEmpty })) {
$0.firstname!.prefix(1).capitalized
}
This is my output:
["D": [motto.User(id: Optional(1), firstname: Optional("Dan"), lastname: Optional("Meeler"), email: Optional("time#example.com"))], "M": [coiqo.User(id: Optional(3), firstname: Optional("Mia"), lastname: Optional("Kallas"), email: Optional("mia#ka.com"))]]
This is the error I got:
Cannot subscript a value of type '[String : [User]]' with an index of type 'Int'
In this function for tableview:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].count
}
How can I get this array to work in a tableview?
Update
I just had to add this to dasblinkenlight answer and it worked!
if(groupKeys.count > 0) {
return sections[groupKeys[section]]!.count
} else {
return sections.count
}
Your self.sections is Dictionary, and dictionaries are unordered.
Once you've made user groups from API results, make a separate array composed of group keys:
let groupKeys : [String] = Array(self.sections.keys)
Sort that array in the way that you wish your sections to appear (alphabetical, reverse alphabetical, natural, etc.)
Now you can write your function like this:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[groupKeys[section]].count
}
This question already has an answer here:
What are the new "for", "at", "in" keywords in Swift3 function declarations?
(1 answer)
Closed 6 years ago.
I have just opened a swift 2 project with last Xcode version.
Xcode suggest me to auto convert my code to swift 3.
Here is something strange:
func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
func tableView(_ tableView: MyTableView, numberOfRowsInSection section: Int) -> Int
{
return 10
}
If you look, Xcode added a "in" keyword for the numberOfSections method. But he did nothing for the numberOfRowsInSection method.
I do not understand why.
What is this "in" keyword in Swift 3 ?
It's not a keyword. It's the name of the first parameter in the method.
In Swift2 the method was...
func numberOfSections(inTableView: UITableView) -> Int
... and it would be called like...
numberOfSections(tableView)
In Swift 3 there is a lot of emphasis on making function names more verb based and removing redundant inferred or implied type from the method names. Also, the first parameter name of methods is now required.
All these changes lead to the name being updated to what you have seen and the call becomes...
numberOfSections(in: tableView)
You can read more about the changes in Swift 3 in Apple's API Guidelines.
I am new developer in Swift.
I did a single ViewController, with UITableView inside --> list management.
User can add/modify information in the list.
Seems to be OK.
--> Information are stored in DB (CoreData : entity/attributes)
example :
table 1 :
Entity = type of food
Attributes = name : string
Question :
I don't know how to create a view were I can have 2 levels of TableView.
Example :
table 1 :
Entity = type of food
Attributes = name : string
example : vegetables, meat, fruit, ...
in the view, user can add a new kind of food himself (example fish)
table 2 :
Entity = Aliment
Attributes = name : string
example : beef <-- (meat), banana <-- (fruit) etc ...).
but linked with table 1 (beef is meat and not fruit)
how to manage this kind of list in an UIview :
create/modify/delete/display a type of food and add some "aliment" in it ?
like a two level list and list2 is linked with the list 1 ?
Any example in swift ?
That's actually simple, you just have to create a new instance of tableview and add it as a subview of your cell in your cellForRowAtIndexPath method.
Example :
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
let tableview = UITableView(frame: CGRectMake(0, 0, cell.frame.width, 50)
cell.addSubview(tableview)
return cell
}
In the following function:
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return 10
}
is the second argument the result returned by calling the function numberOfRowsInSection with section as the argument? If so, where is it getting section from?
This syntax allows to set a name for an argument that is different from the name of the local variable used to capture that arguments value.
numberOfRowsInSection is the name of the parameter that you use when calling this function.
section is the name of the local variable that holds the value that got passed.
So you would call this function like so:
Int rowCount = tableView(tableView: aTabelView, numberOfRowsInSection: 10);
And in that function, you would use the argument like so:
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return section;
}
numberOfRowsInSection is the argument name when calling the function. section is the argument name from within the function. So, for example, you would call this function as follows:
myObject.tableView(aView, numberOfRowsInSection:4)
but from within the function, you would refer to that 4 as follows:
let valueOfSectionArgument = section