Created
June 16, 2019 22:50
-
-
Save sergdort/65e477aa47ace2f381eb516ef75fd68e to your computer and use it in GitHub Desktop.
Iff and Some operators for #SwiftUI. Inspired on some stuff we use in [Bento](). It lets you chain modifiers instead of doing "if - else" dance π
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
extension View { | |
func iff(_ condition: Bool, _ modifier: (Self) -> AnyView) -> AnyView { | |
if condition { | |
return modifier(self).eraseToAnyView() | |
} | |
return eraseToAnyView() | |
} | |
func some<Value>(_ optional: Value?, modifier: (Value, Self) -> AnyView) -> some View { | |
guard let value = optional else { | |
return self.eraseToAnyView() | |
} | |
return modifier(value, self).eraseToAnyView() | |
} | |
} | |
// Now we can do this | |
ForEach(context.movies.identified(by: \.id)) { movie -> AnyView in | |
MovieCell(movie: movie) | |
.iff(context.movies.last == movie) { (cell) -> AnyView in | |
return cell.onAppear { | |
context.send(event: .fetchNext) | |
} | |
} | |
} | |
// Instead of this | |
ForEach(context.movies.identified(by: \.id)) { movie -> AnyView in | |
if context.movies.last == movie { | |
return MovieCell(movie: movie) | |
.onAppear { | |
// Fetch next batch every time reach to the end of the list | |
context.send(event: .fetchNext) | |
} | |
.eraseToAnyView() | |
} | |
return MovieCell(movie: movie) | |
.eraseToAnyView() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment