Last active
September 30, 2020 03:15
-
-
Save boudhayan/c3b25d0f0290cfb0c1765d7a9128d001 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| protocol AEMValue { } | |
| extension String: AEMValue { } | |
| extension Int: AEMValue { } | |
| struct AEMDictionary<T> { | |
| private let container: [String: T] | |
| init(_ dict: [String: T]) { | |
| container = dict | |
| } | |
| private static func aemDefaultValue(_ type: T.Type) -> T { | |
| var defaultValue: AEMValue | |
| switch type { | |
| case is String.Type: | |
| defaultValue = "Content Unavailable" | |
| case is Int.Type: | |
| defaultValue = 0 | |
| default: | |
| fatalError("Default Value is Missing for \(T.self)") | |
| } | |
| guard let value = defaultValue as? T else { | |
| fatalError("\(T.self) should conform to AEMValue protocol.") | |
| } | |
| return value | |
| } | |
| public func fetch(_ key: String, defaultValue: (T.Type) -> T = aemDefaultValue) -> T { | |
| return container[key] ?? defaultValue(T.self) | |
| } | |
| } | |
| // Initialize AEM dictionary | |
| var dict = AEMDictionary(["name": "boudhayan"]) | |
| // Cast to any supported type | |
| var jj: String = dict.fetch("lastName") | |
| // fetch default value | |
| print(dict.fetch("lastName")) | |
| // expect a different default value other than which was set initially | |
| print(dict.fetch("lastName", defaultValue: { _ in "biswas" })) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment