Skip to content

Instantly share code, notes, and snippets.

@omochi
Created April 10, 2019 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omochi/5b96ab34039203194a0d666bbee1a082 to your computer and use it in GitHub Desktop.
Save omochi/5b96ab34039203194a0d666bbee1a082 to your computer and use it in GitHub Desktop.
protocol Stream {
associatedtype ErrorType: Error
func read() -> Result<Int, ErrorType>
}
class FileStream : Stream {
// 固有のエラー型
enum Error : Swift.Error {
case ioError
case fileNotFound
}
typealias ErrorType = Error
func read() -> Result<Int, Error> { return .success(0) }
}
class MemoryStream : Stream {
typealias ErrorType = Never
func read() -> Result<Int, Never> { return .success(0) }
}
class Parser<S: Stream> {
init(_ s: S) {
self.s = s
}
let s: S
func parse() throws -> Int {
return try s.read().get()
}
}
extension Parser where S.ErrorType == Never {
func parse() -> Int {
switch s.read() {
case .success(let x): return x
// neverなので↓が不要
//case .failure(let e): throw e
}
}
}
func main() throws {
let p1: Parser<FileStream> = Parser(FileStream())
let r1 = try p1.parse()
// こっちはtryが外せる
let p2: Parser<MemoryStream> = Parser(MemoryStream())
let r2 = p2.parse()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment