VAAA VAAA - 6 months ago 21
Swift Question

How to create a Set of class in Swift

I'm trying to create a class that will define the properties that I need for a Expandable Table View. So I need to have a class that inside I can declare a property that reference to the same class (expandable parent row childs).

Here is the code that I have:

public class ExpandableCell
{

var icon : String
/// The title for the cell.
var title: String

/// The childs of the cell
var childs: Set<ExpandableCell> = Set<ExpandableCell>()


}


But Im getting an error:

enter image description here


Any clue on how to solve this?

Answer

You have two issues here.

  1. You need to set default values for your icon and title variables, or create an initializer to set them when the instance is created, or change them to optionals.

  2. Your class must conform to Hashable and Equatable in order to be used as a type in a Set.

Update code:

class ExpandableCell: Hashable, Equatable
{
    var icon : String = ""
    /// The title for the cell.
    var title: String = ""

    /// The childs of the cell
    var childs: Set<ExpandableCell> = Set<ExpandableCell>()

    // MARK: - Hashable
    var hashValue: Int {
        return title.hashValue
    }
}

// MARK: - Equatable
func ==(lhs: ExpandableCell, rhs: ExpandableCell) -> Bool {
    return lhs.title == rhs.title
}

Note: This code assumes that two cells are equal if they have the same title. You may want to change that based on your application/use. If so, change the hashValue to return a unique Int based on whatever makes your cells be considered the same. And update the func ==() in a similar manner. You may need to take into account the children for example.

Comments