Skip to content

Instantly share code, notes, and snippets.

@lingoslinger
Last active September 15, 2023 23:38
Show Gist options
  • Save lingoslinger/8dd4909350b3bd7f315f80ebab4ac21c to your computer and use it in GitHub Desktop.
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
// 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
@lingoslinger
Copy link
Author

See comments in gist for instructions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment