jorjj
jorjj

Reputation: 1619

Swift fatal error: Can't form Range with upperBound < lowerBound

I have a class that I want to add value there with for loop.

This is my class:

public class Expandable {
    public var name: String
    public var id:Int

    init(name: String, id:Int) {
        self.name = name
        self.id = id
    }

I can add manually like that :

let a = [Expandable(name:"aaa", id: 12)]

But when I try with for loop, it doesn't work at all.

for allin in items{
    sidebarMenuItem?.append(Expandable(name: allin["Code"] as! String, id: allin["Id"] as! Int))
}

Items data works perfectly, but sidebarMenuItem is getting Optional(MyProjectName.Expandable) value when I print it.

UPDATE :

I realized that I'm getting the datas well, but I get an error into expandCell function :

fatal error: Can't form Range with upperBound < lowerBound

My expandCell function :

private func expandCell(tableView: UITableView, index: Int) {
    // Expand Cell (add ExpansionCells
    if let expansions = sideBarData?[index]?.expandable {
        for i in 1...expansions.count {
            sideBarData?.insert(nil, at: index + i)
            tableView.insertRows(at: [NSIndexPath(row: index + i, section: 0) as IndexPath] , with: .top)
        }
    }
}

Upvotes: 1

Views: 9897

Answers (5)

Wissa
Wissa

Reputation: 1592

SWIIFT 4

To form a range from upperBound to lowerBound use stride as by this documentation page: Generic Function stride(from:to:by:)

for i in stride(from: 10, through: 5, by: -1) { print(i) }

and stride through if you want to include the lowerBound: Generic Function stride(from:through:by:)

Upvotes: 1

Midhun
Midhun

Reputation: 2197

// swift 3.0
let k = 5
for i in stride(from: 10, through: k, by: 1) { print("i=\(i)") }
for i in stride(from: 10, to: k, by: 1) { print("i=\(i)") }

Upvotes: 1

Jaime Sendra Domenech
Jaime Sendra Domenech

Reputation: 54

try this:

  private func expandCell(tableView: UITableView, index: Int) {
        // Expand Cell (add ExpansionCells
        if let expansions = sideBarData?[index]?.expandable {
            //0 because your first item starts at 0
            for i in 0...expansions.count {
                sideBarData?.insert(nil, at: index + i)
                tableView.insertRows(at: [NSIndexPath(row: index + i, section: 0) as IndexPath] , with: .top)
            }
        }
    }

Upvotes: 0

Krishna Kumar
Krishna Kumar

Reputation: 1652

I am not sure how is your expansions structure. But I am guessing it for some cell it might be that your expansion count is 0. That is why its giving this error when your start index is 1 and end index is 0.

Upvotes: 0

Bilal
Bilal

Reputation: 19156

sidebarMenuItem is optional because you have declared it optional. Try this.

var sidebarMenuItem = [Expandable]()

for allin in items{
    sidebarMenuItem.append(Expandable(name: allin["Code"] as! String, id: allin["Id"] as! Int))
}

Upvotes: 1

Related Questions