Skip to content

Instantly share code, notes, and snippets.

@foxicode
Created July 17, 2022 17:11
Show Gist options
  • Select an option

  • Save foxicode/f9dc6b0a1ca17e21e94e665c4ffda891 to your computer and use it in GitHub Desktop.

Select an option

Save foxicode/f9dc6b0a1ca17e21e94e665c4ffda891 to your computer and use it in GitHub Desktop.
Protocol extensions in Swift
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