Skip to content

Instantly share code, notes, and snippets.

@iAmVishal16
Created September 4, 2024 18:24
Show Gist options
  • Select an option

  • Save iAmVishal16/8c0c8a34aba0d2aee9c848fb2fce4ddb to your computer and use it in GitHub Desktop.

Select an option

Save iAmVishal16/8c0c8a34aba0d2aee9c848fb2fce4ddb to your computer and use it in GitHub Desktop.
Example of Associated types in Swift Protocols
protocol Operations {
associatedtype ItemType
func operation(arg1: ItemType, arg2: ItemType) -> ItemType
}
struct MathAddition: Operations {
func operation(arg1: Int, arg2: Int) -> Int {
return arg1 + arg2
}
}
struct ConcateStrings: Operations {
func operation(arg1: String, arg2: String) -> String {
return arg1 + arg2
}
}
let op = MathAddition()
let result = op.operation(arg1: 1, arg2: 2)
print(result)
let op1 = ConcateStrings()
let result1 = op1.operation(arg1: "fire", arg2: "fighter")
print(result1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment