Skip to content

Instantly share code, notes, and snippets.

@eliperkins
Last active November 25, 2015 01:32
Show Gist options
  • Save eliperkins/fba1f07f047ba3e73972 to your computer and use it in GitHub Desktop.
Save eliperkins/fba1f07f047ba3e73972 to your computer and use it in GitHub Desktop.
// Given that a protocol unifies two types: BlogPost and PhotoPost...
protocol PostType {
var title: String { get }
}
struct BlogPost: PostType {
let title = "My Hot New Blog Post"
}
struct PhotoPost: PostType {
let title = "Photos from Vacation in Cleveland with Lebron"
}
// And that we have an array of items of such protocol...
let posts: [PostType] = [BlogPost(), PhotoPost()]
// And thus we construct a protocol to communicate view models of these types...
protocol PostTypeViewModel {
typealias Post = PostType
var post: Post { get }
}
struct BlogPostViewModel: PostTypeViewModel {
let post: BlogPost
}
struct PhotoPostViewModel: PostTypeViewModel {
let post: PhotoPost
}
// ...how do we generically go from PostType -> PostTypeViewModel while getting out the correct concrete types of BlogPostViewModel and PhotoPostViewModel?
let postViewModels: [PostTypeViewModel] = posts.map( *** What do I do here? *** )
// ...so that we could theoretically get an array of post titles out?
postViewModels.map { $0.post.title }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment