Last active
May 30, 2021 14:03
-
-
Save startover205/6ed303c35fc1e76c3104ddafb81782f5 to your computer and use it in GitHub Desktop.
An example of composition.
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
import Foundation | |
protocol VideoFilter { | |
func addFilter(completion: @escaping (Bool) -> Void) | |
} | |
struct ChainedFilter: VideoFilter { | |
let primary: VideoFilter | |
let next: VideoFilter | |
func addFilter(completion: @escaping (Bool) -> Void) { | |
primary.addFilter { (success) in | |
if success { | |
next.addFilter(completion: completion) | |
} else { | |
// depend on how to handle failure | |
completion(false) | |
} | |
} | |
} | |
} | |
extension VideoFilter { | |
func chain(_ filter: VideoFilter) -> VideoFilter { | |
ChainedFilter(primary: self, next: filter) | |
} | |
} | |
struct TrimmerFilter: VideoFilter { | |
func addFilter(completion: @escaping (Bool) -> Void) { | |
// implement logic | |
print("Trimmed!") | |
completion(true) | |
} | |
} | |
struct SubtileFilter: VideoFilter { | |
func addFilter(completion: @escaping (Bool) -> Void) { | |
// implement logic | |
print("Added Subtitle!") | |
completion(true) | |
} | |
} | |
struct SpeedChangerFilter: VideoFilter { | |
func addFilter(completion: @escaping (Bool) -> Void) { | |
// implement logic | |
print("Changed Speed!") | |
completion(true) | |
} | |
} | |
let filter = TrimmerFilter() | |
.chain(SubtileFilter()) | |
.chain(SpeedChangerFilter()) | |
filter.addFilter { (success) in | |
if success { | |
print("All Process Succeeded!") | |
} else { | |
print("Process Failed!") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment