Last active
March 12, 2019 13:29
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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