Set containing enum containing enum with associated value

Given:

public enum Endian {                  
    case big, little                  
}                                     
                                      
public enum DataConversionOption {    
    case encoding(String.Encoding)    
    case endian(Endian)               
}                                     

Can the following be simplified?

init(conversionOptions: Set<DataConversionOption>) {
    for option in conversionOptions {                                            
        if case .endian(let endian) = option {                                   
            number = (endian == .big) ? number.bigEndian : number.littleEndian   
        }                                                                        
    }                                                                            
}

Can I use the contains or first (or some other) method of Set to extract the associated value of the Endian enum if the conversionOptions Set contains one?

Well you could write a couple of methods like so:

extension DataConversionOption {
  var endianness: Endian? {
    if case .endian(let x) = self { return x }
    return nil
  }
}

extension Sequence where Element == DataConversionOption {
  var endianness: Endian? {
    return first{ $0.endianness != nil }?.endianness
  }
}

Usage:

if let endian = conversionOptions.endianness {
  // `endian` is of type `Endian` and can be used here
}
1 Like

Both answers look good. Now to decide which way I want to go. Thanks!!