Created
April 10, 2019 09:49
-
-
Save omochi/5b96ab34039203194a0d666bbee1a082 to your computer and use it in GitHub Desktop.
This file contains 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 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