Swift - Passing different enum types for same variable to a class

Viewed 2113

How can I pass different enums types to a same variable, identify its type later and use its raw values to do some operations?

I have two enums Menu1 and Menu2 of type String. I like to pass an array of enums to another class which shows submenu. I like to pass enum to same variable since I may add another menu in future.

4 Answers

We can use protocol and send any enum object and no need to type cast the object to access the rawValue. we can pass different types of enums and read the values.

protocol AttributeKeyProtocol {
    var value: String { get }
}

struct AttributeData {
     let key: AttributeKeyProtocol
     let value: String
     init(key: AttributeKeyProtocol, value: String) {
        self.key = key
        self.value = value
    }
}

enum MyClasses: AttributeKeyProtocol {
    var value: String {
        switch self {
        case .one(.logo):
            return"logo"
        default:
            return "all"
        }
    }
    
    case one(MyComputerClasses)
    case two
    
    enum MyComputerClasses: String, AttributeKeyProtocol {
        case logo
        case pascal
        
        var value: String {
            return self.rawValue
        }
    }
}

MyClasses implementing 'AttributeKeyProtocol'


enum MyCourses: String, AttributeKeyProtocol {
    case three = "psd_ssj_sdoj"
    case four
    
    var value: String {
        return self.rawValue
    }
}

class NewSDK {
    func track(name: String, type: String, attributes: [AttributeData]?) {
        print("attributes:  \(attributes?.first?.key.value)")
        print("attributes:  \(attributes?.last?.key.value)")
    }
}

NewSDK().track(name: "sfd", type: "dsfd", attributes: [.init(key: MyClasses.one(.logo) , value: "sdfd"),
                                                         .init(key: MyCourses.three, value: "sfdfsd")])
Related