Created
July 17, 2022 17:11
-
-
Save foxicode/f9dc6b0a1ca17e21e94e665c4ffda891 to your computer and use it in GitHub Desktop.
Protocol extensions in Swift
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
| enum Access { | |
| case create | |
| case read | |
| case write | |
| case delete | |
| } | |
| protocol PFile { | |
| func open(access: Access) | |
| func close() | |
| } | |
| protocol PReadableFile: PFile { | |
| func openForReading() | |
| func readText() -> String | |
| func get() -> String | |
| } | |
| extension PReadableFile { | |
| func openForReading() { | |
| open(access: .read) | |
| } | |
| func readText() -> String { | |
| var string: String = "" | |
| // ... | |
| return string | |
| } | |
| func get() -> String { | |
| openForReading() | |
| let string = readText() | |
| close() | |
| return string | |
| } | |
| } | |
| protocol PWritableFile: PFile { | |
| func openForWriting() | |
| func write(text: String) | |
| func set(text: String) | |
| } | |
| extension PWritableFile { | |
| func openForWriting() { | |
| open(access: .write) | |
| } | |
| func write(text: String) { | |
| // ... | |
| } | |
| func set(text: String) { | |
| openForWriting() | |
| write(text: text) | |
| close() | |
| } | |
| } | |
| class File: PFile { | |
| func open(access: Access) { | |
| // ... | |
| } | |
| func close() { | |
| // ... | |
| } | |
| } | |
| class MyFile: File, PReadableFile, PWritableFile { | |
| // This file has all functions | |
| // Nothing needs to be implemented here | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment