Skip to content

Instantly share code, notes, and snippets.

@ole
Last active August 29, 2015 14:25
Show Gist options
  • Save ole/a3638f0bc845cbcc2772 to your computer and use it in GitHub Desktop.
Save ole/a3638f0bc845cbcc2772 to your computer and use it in GitHub Desktop.
Equatable protocols in Swift. A reply to Brent Simmons’s post "Secret Projects Diary #2: Swift 2.0 Protocols" (http://inessential.com/2015/07/19/secret_projects_diary_2_swift_2_0_prot).
//: Playground - noun: a place where people can play
import Cocoa
protocol Feed : Equatable {
var url: String {get}
}
protocol Folder {
// This is new:
typealias FeedType
var feeds: [FeedType] {get}
func addFeeds(feedsToAdd: [FeedType])
}
func ==<T: Feed>(lhs: T, rhs: T) -> Bool {
return lhs.url == rhs.url
}
class LocalFeed: Feed {
var url: String
init(url: String) {
self.url = url
}
}
class LocalFolder: Folder {
// Notice I’m using concrete types (LocalFeed) for the protocol's interface here.
// You can't just specify Feed because the compiler must be able to make sure that all
// places where the protocol specifies Feed have the same concrete type.
var feeds = [LocalFeed]()
func addFeeds(feedsToAdd: [LocalFeed]) {
for oneFeed in feedsToAdd {
if !feeds.contains(oneFeed) {
feeds += [oneFeed]
}
}
}
}
@ole
Copy link
Author

ole commented Jul 19, 2015

Edit: I renamed the typealias Feed to typealias FeedType to avoid confusion with the Feed protocol.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment