Created
May 17, 2020 12:11
-
-
Save yoxisem544/df39ead975778d0db593b16641fd0e4e 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
import Foundation | |
struct Foobar<T: Equatable> { | |
let value: T | |
let count: Int | |
} | |
extension Collection { | |
func sumOfCounts<T>(where predicate: (T) -> Bool) -> Int where Element == Foobar<T> { | |
reduce(0, { $0 + (predicate($1.value) ? $1.count : 0) }) | |
} | |
func printAll<T>() where Element == Foobar<T> { | |
forEach({ e in print(e.value) }) | |
} | |
} | |
let array = [ | |
Foobar<String>(value: "one", count: 1), | |
Foobar<String>(value: "two", count: 2), | |
Foobar<String>(value: "three", count: 3), | |
] | |
array.printAll() | |
array.sumOfCounts(where: { $0.contains("one") }) | |
let aa: [String?] = [ | |
"", nil, "1" | |
] | |
extension Array { | |
func filterNil<T>() -> [T] where Element == Optional<T> { | |
compactMap({ $0 }) | |
} | |
} | |
aa.filterNil() | |
protocol OptionalType { | |
associatedtype Wrapped | |
var value: Wrapped? { get } | |
} | |
extension Optional: OptionalType { | |
var value: Wrapped? { self } | |
} | |
extension Array where Element: OptionalType { | |
func filterShit() -> [Element.Wrapped] { | |
compactMap({ $0.value }) | |
} | |
} | |
aa.filter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired from: https://twitter.com/jegnux/status/1259936037721292800