Skip to content

Instantly share code, notes, and snippets.

@kezzico
Last active December 11, 2023 19:45
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 kezzico/bf77d581a2f6f6f197963c279c698893 to your computer and use it in GitHub Desktop.
Save kezzico/bf77d581a2f6f6f197963c279c698893 to your computer and use it in GitHub Desktop.
Code Sample: Cache in Swift
/*
You are building a small part of this iOS application that needs to implement a simple key-value type of cache. In Swift, you will need to implement a cache class with the functions add, get, and size.
The add function takes two parameters, a key and value and adds the pair to the local cache. When an item is added to the cache, this function should return the string "added" and if the item already existed in the cache, this function should return the string "overwritten"
The get function attempts to retrieve an item from the cache based on the key parameter passed in. If the item exists in the cache, return the value, otherwise return the string "miss"
The size function simply returns the number of items in the cache.
Your goal is to implement the cache class so the function calls in the main method work properly. The output of your program should be a final string with the function outputs separated by a space.
The iOS device on the right side takes in your output and presents it on screen in a formatted way so you can easily visualize it.
Example Input
cache.add("a", "value1")
cache.add("b", "value2")
cache.add("b", "value2")
cache.add("rrrrr", "nothing")
cache.get("hello")
cache.get("world")
cache.get("b")
cache.get("rrrrr")
cache.size()
Example Output
added added overwritten added miss miss value2 nothing 3
*/
import Foundation
// create a cache class/interfact here that allows the functions below to run
// todo
class Cache {
private var dict:[String:String] = [:]
func add(_ key: String, _ value: String) -> String {
let output = dict[key] == nil ? "added" : "overwritten"
dict[key] = value
// print(output)
return output;
}
func get(_ key: String) -> String {
guard let output = dict[key] else {
// print("miss")
return "miss"
}
// print(output)
return output;
}
func size() -> Int {
let output = dict.count
// print(output)
return output
}
}
let cache = Cache();
cache.add("article-123", "https://coderbyte.com/article-123")
cache.add("article-456", "https://coderbyte.com/article-456"))
cache.add("how-to-code-444", "https://coderbyte.com/how-to-code-444")
cache.get("first-article")
cache.get("second-article")
cache.get("article-456")
cache.add("article-123", "https://coderbyte.com/article-123")
cache.size()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment