Home > Software design >  is it possible swift func get <T> enum?
is it possible swift func get <T> enum?

Time:11-17

there's two func get enum from parameter, is it possible those func combined just one func?

func rushdownSetupListener(event: RushdownListenEvent, handler: @escaping ([Any], SocketAckEmitter) -> Void) -> UUID? {
        guard let client = self.client else {
            return nil
        }
        
        let listenerId = client.on(event.rawValue, callback: handler)
        
        return listenerId
    }
    
    func hystoriaSetupListener(event: HystoriaListenEvent,handler: @escaping ([Any], SocketAckEmitter) -> Void) -> UUID? {
        guard let client = client else {
            return nil
        }
        let listenerId = client.on(event.rawValue, callback: handler)
        
        return listenerId
    }

CodePudding user response:

Since both of those enums have a String as their raw value, they both conform to RawRepresentable where RawValue == String. Therefore, you can introduce a generic parameter type constrained to exactly that:

func setupListener<EventType>(event: EventType, handler: @escaping ([Any], SocketAckEmitter) -> Void) -> UUID? 
    where EventType: RawRepresentable, EventType.RawValue == String {
    guard let client = self.client else {
        return nil
    }
    
    let listenerId = client.on(event.rawValue, callback: handler)
    
    return listenerId
}

You should be able to even simplify the function body to just:

client?.on(event.rawValue, callback: handler)
  • Related