Skip to content

Commit 8db5f68

Browse files
committed
Update README about type safety
1 parent 66d76c1 commit 8db5f68

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

README.md

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,34 @@ All you need to do is to specify the configuration you want with `DiskConfig` an
6767
let diskConfig = DiskConfig(name: "Floppy")
6868
let memoryConfig = MemoryConfig(expiry: .never, countLimit: 10, totalCostLimit: 10)
6969

70-
let storage = try? Storage(diskConfig: diskConfig, memoryConfig: memoryConfig)
70+
let storage = try? Storage(
71+
diskConfig: diskConfig,
72+
memoryConfig: memoryConfig,
73+
transformer: TransformerFactory.forCodable(ofType: User.self) // Storage<User>
74+
)
75+
```
76+
77+
### Generic, Type safety and Transformer
78+
79+
All `Storage` now are generic by default, so you can get a type safety experience. Once you create a Storage, it has a type constraint that you don't need to specify type for each operations afterwards.
80+
`
81+
If you want to change the type, `Cache` offers `transform` functions, look for `Transformer` and TransformerFactory` for built-in transformers.
82+
83+
```swift
84+
let storage: Storage<User> = ...
85+
storage.setObject(superman, forKey: "user")
86+
87+
let imageStorage = storage.transformImage() // Storage<UIImage>
88+
imageStorage.setObject(image, forKey: "image")
89+
90+
let stringStorage = storage.transformCodable(ofType: String.self) // Storage<String>
91+
stringStorage.setObject("hello world", forKey: "string")
7192
```
7293

94+
Each transformation allows you to work with a specific type, however the underlying caching mechanism remains the same, you're working with the same `Storage`, just with different type annotation. You can also create different `Storage` for each type if you want.
95+
96+
`Transformer` is necessary because the need of serialising and deserialising objects to and from `Data` for disk persistency. `Cache` provides default `Transformer ` for `Data`, `Codable` and `UIImage/NSImage`
97+
7398
#### Codable types
7499

75100
`Storage` supports any objects that conform to [Codable](https://developer.apple.com/documentation/swift/codable) protocol. You can [make your own things conform to Codable](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) so that can be saved and loaded from `Storage`.
@@ -102,6 +127,8 @@ public enum StorageError: Error {
102127
case encodingFailed
103128
/// The storage has been deallocated
104129
case deallocated
130+
/// Fail to perform transformation to or from Data
131+
case transformerFail
105132
}
106133
```
107134

0 commit comments

Comments
 (0)