Skip to content

Instantly share code, notes, and snippets.

@stinger
Forked from sergdort/Iff.swift
Created June 17, 2019 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stinger/8e7a54d183c60a123ebda8a7116b411a to your computer and use it in GitHub Desktop.
Save stinger/8e7a54d183c60a123ebda8a7116b411a 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