Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would one implement a bidirectional map in Swift?

I am currently in need of a performant bidirectional map. In Swift, a dictionary can be reversed, however, that will return a tuple of the types it is made of, not a counterpart dictionary.

Is there a library for that or does someone have ideas on how to address this issue?

Thanks

like image 697
Lukas Süsslin Avatar asked Nov 02 '17 11:11

Lukas Süsslin


1 Answers

With Swift 4 you could easily make your own using a generic struct:

struct BidiMap<F:Hashable,T:Hashable>
{
   private var _forward  : [F:T]? = nil
   private var _backward : [T:F]? = nil

   var forward:[F:T]  
   { 
      mutating get 
      { 
        _forward = _forward ?? [F:T](uniqueKeysWithValues:_backward?.map{($1,$0)} ?? [] ) 
        return _forward!
      }
      set { _forward = newValue; _backward = nil }
   }

   var backward:[T:F]  
   { 
      mutating get 
      { 
        _backward = _backward ?? [T:F](uniqueKeysWithValues:_forward?.map{($1,$0)} ?? [] ) 
        return _backward!
      }
      set { _backward = newValue; _forward = nil }
   }

   init(_ dict:[F:T] = [:])
   { forward = dict  }

   init(_ values:[(F,T)])
   { forward = [F:T](uniqueKeysWithValues:values) }

   subscript(_ key:T) -> F? 
   { mutating get { return backward[key] } set{ backward[key] = newValue } }

   subscript(_ key:F) -> T?
   { mutating get { return forward[key]  } set{ forward[key]  = newValue } }

   subscript(to key:T) -> F? 
   { mutating get { return backward[key] } set{ backward[key] = newValue } }

   subscript(from key:F) -> T?
   { mutating get { return forward[key]  } set{ forward[key]  = newValue } }

   var count:Int { return _forward?.count ?? _backward?.count ?? 0 }
}

var bd = BidiMap( [1:"A", 2:"B", 3:"C"] )
bd[1] // "A"
bd["B"] // 2
bd[4] = "D"
bd[to:"D"] // 4
bd[from:4] // "D"

var int2int = BidiMap( [1:2, 5:3] )
int2int[from:1] // 2
int2int[to:3] // 5

[EDIT] improved performance a bit by delaying rebuilding of mirror dictionary until it is actually referenced.

like image 119
Alain T. Avatar answered Nov 01 '22 15:11

Alain T.