Skip to content

Instantly share code, notes, and snippets.

@mrugeshtank
Created December 31, 2022 05:36
Show Gist options
  • Save mrugeshtank/4bafee76e144ee36d727ebcaf63bbcbc to your computer and use it in GitHub Desktop.
Save mrugeshtank/4bafee76e144ee36d727ebcaf63bbcbc to your computer and use it in GitHub Desktop.
associatedtype in swift explanation with example
protocol ModelManager {
associatedtype NewModel
associatedtype Collection: Swift.Collection where Collection.Element == NewModel
associatedtype Query
func models(matching query: Query) -> Collection
}
struct User {
var name: String
var age: Int
}
class UserManager: ModelManager {
typealias NewModel = User
var allUsers: [User]!
enum Query {
case name(String)
case ageRange(Range<Int>)
}
func models(matching query: Query) -> [User] {
switch query {
case .name(let name):
return allUsers.filter({$0.name.contains(name)})
case .ageRange(let ageRange):
// return allUsers.filter({$0.age > ageRange.lowerBound && $0.age < ageRange.upperBound})
return allUsers.filter({ageRange.contains($0.age)})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment