iHarshil
iHarshil

Reputation: 779

How to return numberOfRowsInSection?

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:

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

Answers (3)

Keshav Raj
Keshav Raj

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

Arnab
Arnab

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

Hardik Bar
Hardik Bar

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

Related Questions