有可能 swift func get <T> 枚举吗?

is it possible swift func get <T> enum?

有两个函数从参数中获取枚举, 有没有可能这些函数只合并一个函数?

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
    }

因为这两个枚举都有一个 String 作为它们的原始值,所以它们都符合 RawRepresentable 其中 RawValue == String。因此,您可以引入一个严格限制为的通用参数类型:

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
}

您甚至应该能够将函数体简化为:

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