Created
December 31, 2022 05:36
-
-
Save mrugeshtank/4bafee76e144ee36d727ebcaf63bbcbc to your computer and use it in GitHub Desktop.
associatedtype in swift explanation with example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol ModelManager { | |
associatedtype NewModel | |
associatedtype Collection: Swift.Collection where Collection.Element == NewModel | |
associatedtype Query | |
func models(matching query: Query) -> Collection | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct User { | |
var name: String | |
var age: Int | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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