Last active
September 15, 2023 23:38
-
-
Save lingoslinger/8dd4909350b3bd7f315f80ebab4ac21c to your computer and use it in GitHub Desktop.
Swift: Return the product of the even values in a dictionary where the values are inside of strings
This file contains 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
// I publicly share any answers to "coding challenges" I receive as a part of the interview process | |
// copy/paste this into an Xcode playground or the code challenge repl of choice | |
let values = [5:"4", 6:"5", 2:"6", nil:nil, 4:"5", 3:"apple"] | |
func evenProduct(_ numbers: [Int?: String?]) -> Int { | |
return Array(numbers.values) | |
.compactMap{$0} // remove nil values and unwrap optionals | |
.compactMap{Int($0)} // remove strings that return nil when converted to an Int, leaving an array of Ints | |
.filter{$0 % 2 == 0} // even numbers | |
.reduce(1, *) // product | |
} | |
print(evenProduct(values)) | |
// 24 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See comments in gist for instructions