Created
September 2, 2019 22:23
-
-
Save jimmyhoran/eec8d7a0e4f4d499641e4c24ed6b0dd4 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
var dict: [String: Any?] = ["a": nil, "b": 0, "c": 1] | |
// 1. Map and comapctMap | |
// This works. Although the dictionary value is still optional even though it could never be nil here 👍 | |
let mappedDict = dict.map { return $0.value != nil ? $0 : nil }.compactMap { $0 } | |
print(mappedDict) | |
// 2. Filter | |
// Filtering achieves the same | |
let filteredDict = dict.filter { $0.value != nil } | |
print(filteredDict) | |
// 3. Filter and mapValues | |
// To make value non-optional after filtering you can map the values and unwrap them to get the best result. | |
let filteredNonOptionalDict: [String: Any] = dict.filter { $0.value != nil }.mapValues { $0! } | |
print(filteredNonOptionalDict) | |
// TL;DR | |
let newDict: [String: Any] = dict.filter { $0.value != nil }.mapValues { $0! } | |
// gives you a dictrionary of [String: Any] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment