Skip to content

Instantly share code, notes, and snippets.

@sergdort
Created June 16, 2019 22:50
Show Gist options
  • Save sergdort/65e477aa47ace2f381eb516ef75fd68e to your computer and use it in GitHub Desktop.
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 πŸš€
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