Reputation: 779
I really need help as I am new to Swift. I am facing an issue where I don't find a way to return numberOfRowsInSection
Scenario:
I have 3 numberOfSections in tableview which I am returning from sectionArray, which is as follows:
{
"mbsdcie6_2_1": "Incomer 132 KV Parameters",
"mbsdcie6_2_2": [
3,
6,
4,
5,
8,
30,
31,
7,
18,
29,
1
]
},
{
"mbsdcie6_2_1": "SMS2 Parameters",
"mbsdcie6_2_2": [
9,
10,
11,
12,
13,
14
]
},
{
"mbsdcie6_2_1": "SMS 1 Parameters",
"mbsdcie6_2_2": [
15,
17
]
}
]
}
Using above array, I can return numberOfSections like this:
func numberOfSections(in tableView: UITableView) -> Int {
return self.sectionArray.count
}
But, how to return numberOfRowsInSection using sectionArray ??
Note:
I want numberOfRows from "mbsdcie6_2_2" key of sectionArray
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return "numberOfRows" // What to return here?
}
if section == 1 {
return "numberOfRows"
}
if section == 2 {
return "numberOfRows"
}
return 0
}
Edit 1
This is how I added data into sectionArray:
// It comes from another webservice, so I added it to userdefaults.
let headers = swiftyJSonVar["message"][0]["mbsdcie6"]["mbsdcie6_2"].arrayObject
kUserDefault.set(headers, forKey: kHeadersArray)
// In my another ViewController, I am retrieving it like this:
var sectionArray = [Dictionary<String, Any>]()
override func viewWillAppear(_ animated: Bool) {
sectionArray = kUserDefault.array(forKey: kHeadersArray) as! [Dictionary<String, Any>]
print(sectionArray)
}
I know it could be silly and It's way too easy but somehow I am stucked as I am new to it. Any help would be appreciated, Thanks!
Upvotes: 1
Views: 1925
Reputation: 476
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if sectionArray.indices.contains(section),
let sectionContent = sectionArray[section]["mbsdcie6_2_2"] as? [Int] {
return sectionContent.count
} else {
return 0
}
}
Upvotes: 2
Reputation: 4356
try this:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let singleSection = self.sectionArray[section]
if let rows = singleSection["mbsdcie6_2_2"] as? [Int] {
return rows.count
} else {
return 0
}
}
Upvotes: 1
Reputation: 1760
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if !sectionArray.isEmpty {
let sectionContent = sectionArray[section]["mbsdcie6_2_2"] as? [Int]
return sectionContent.count
} else {
return 0
}
}
Upvotes: 3