-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTask.swift
55 lines (44 loc) · 1.38 KB
/
Task.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Implement mobile phone storage protocol
// Requirements:
// - Mobiles must be unique (IMEI is an unique number)
// - Mobiles must be stored in memory
protocol MobileStorageProtocol {
func getAll() -> Set<Mobile>
func findByImei(_ imei: String) -> Mobile?
func save(_ mobile: Mobile) throws -> Mobile
func delete(_ product: Mobile) throws
func exists(_ product: Mobile) -> Bool
}
struct Mobile: Hashable {
let imei: String
let model: String
}
enum MobileStorageError: Error {
case mobileAlreadyExistsError
case mobileImeiAlreadyExistsError
case mobileNotFound
}
class MobileStorage: MobileStorageProtocol {
var mobiles: Set<Mobile> = Set<Mobile>()
func getAll() -> Set<Mobile> {
return mobiles
}
func findByImei(_ imei: String) -> Mobile? {
return mobiles.first { $0.imei == imei }
}
func save(_ mobile: Mobile) throws -> Mobile {
if findByImei(mobile.imei) != nil {
throw MobileStorageError.mobileImeiAlreadyExistsError
}
let (inserted, newMobile) = mobiles.insert(mobile)
return newMobile
}
func delete(_ product: Mobile) throws {
guard let deleted = mobiles.remove(product) else {
throw MobileStorageError.mobileNotFound
}
}
func exists(_ product: Mobile) -> Bool {
mobiles.contains(product)
}
}