Skip to content

Instantly share code, notes, and snippets.

@mingsai
Created February 12, 2016 17:50
Show Gist options
  • Select an option

  • Save mingsai/b90d5a5d0d5de8ac7593 to your computer and use it in GitHub Desktop.

Select an option

Save mingsai/b90d5a5d0d5de8ac7593 to your computer and use it in GitHub Desktop.
Swift Dictionary extensions to return all keys for a value, et al.
//
// DictionaryExtensions.swift
//
//
// Created by Tommie N. Carter, Jr., MBA on 12/14/15.
// Copyright © 2015 MING Technology. All rights reserved.
//
import Foundation
extension Dictionary where Value : Equatable {
// func allKeysForValue<K, V : Equatable>(dict: [K : V], val: V) -> [K] {
// return dict.filter{ $0.1 == val }.map{ $0.0 }
// }
func allKeysForValue(val : Value) -> [Key] {
return self.filter { $1 == val }.map { $0.0 }
}
func someKeyFor(value: Value) -> Key? {
guard let index = indexOf({ $0.1 == value }) else {
return nil
}
return self[index].0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment