Skip to content

Instantly share code, notes, and snippets.

@GregoryMaks
Last active August 13, 2017 10:49
Show Gist options
  • Save GregoryMaks/a11a4780da3e85d0dfe45073f68e9967 to your computer and use it in GitHub Desktop.
Save GregoryMaks/a11a4780da3e85d0dfe45073f68e9967 to your computer and use it in GitHub Desktop.
// ***
// Option 1 (functional approach, minimum variables)
// ***
let pagingTuple: (String?, String?) = try zip(
dataNode.validatedOptionalValue(forKey: "after"),
dataNode.validatedOptionalValue(forKey: "before")
)
let pagingMarker = unwrap(pagingTuple)
.flatMap { RedditListingResult<ServerModel>.PagingMarker(before: $0.0, after: $0.1) }
// ***
// Option 2 (classic swifty way)
// ***
var pagingMarker: RedditListingResult<ServerModel>.PagingMarker? = nil
if let after = try dataNode.validatedOptionalValue(forKey: "after") as String?,
let before = try dataNode.validatedOptionalValue(forKey: "before") as String?
{
pagingMarker = .init(before: before, after: after)
}
// ***
// Functional helper methods
// ***
func zip<T, P>(_ value1: @autoclosure () throws -> T, _ value2: @autoclosure () throws -> P) throws -> (T, P) {
return (try value1(), try value2())
}
func unwrap<T, P>(_ tuple: (T?, P?)) -> (T, P)? {
return (tuple.0 != nil && tuple.1 != nil) ? (tuple.0!, tuple.1!) : nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment