Skip to content

Instantly share code, notes, and snippets.

@Tulakshana
Last active March 12, 2019 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tulakshana/6ef2be58ba264589c88b7ddffa4bb854 to your computer and use it in GitHub Desktop.
Save Tulakshana/6ef2be58ba264589c88b7ddffa4bb854 to your computer and use it in GitHub Desktop.
At one of the iOS developer interviews I went, I was asked to replicate the functionality of a Dictionary. I thought I would share what I came up with. Improvements are most welcome.
import Foundation
// This class simulates SWift's dictionary class
class MyDictionary <Key: Equatable, Value> {
private var values: [Value] = []
private var keys: [Key] = []
func set(value: Value, key: Key) {
if keys.contains(key), let index = keys.firstIndex(of: key) {
values[index] = value
} else {
values.append(value)
keys.append(key)
}
}
func get(key: Key) -> Value? {
if let index = keys.firstIndex(of: key) {
return values[index]
}
return nil
}
}
var dic: MyDictionary<String, String> = MyDictionary()
dic.set(value: "Sam", key: "ceo")
dic.set(value: "Sam Inc.", key: "company")
dic.set(value: "20", key: "employees")
print("Company: " + (dic.get(key: "company") ?? ""))
print("CEO: " + (dic.get(key: "ceo") ?? ""))
print("Number of employees: " + (dic.get(key: "employees") ?? ""))
dic.set(value: "30", key: "employees")
print("Number of employees: " + (dic.get(key: "employees") ?? ""))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment