Created
September 4, 2024 18:24
-
-
Save iAmVishal16/8c0c8a34aba0d2aee9c848fb2fce4ddb to your computer and use it in GitHub Desktop.
Example of Associated types in Swift Protocols
This file contains hidden or 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 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