Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Result<T> V.S. Result<T, E>

Result<T> V.S. Result<T, E>

Eac0bf787b5279aca5e699ece096956e?s=128

Yasuhiro Inami

November 21, 2017
Tweet

Transcript

  1. Result<T> V.S. Result<T, E> 2017/11/21 ؔ੢ϞόΠϧΞϓϦݚڀձ in ؔ౦ Yasuhiro Inami

    / @inamiy
  2. None
  3. None
  4. None
  5. // Proposal, Τϥʔܕύϥϝʔλͳ͠ public enum Result<Value> { case success(Value) case

    failure(Swift.Error) } // V.S. // Τϥʔܕύϥϝʔλ͋Γ public enum Result<Value, Error: Swift.Error> { case success(Value) case failure(Error) }
  6. None
  7. Result<T, E> (V.S. Result<T>) • GOOD: ResultʹΤϥʔܕΛຒΊࠐΉ͜ͱ͕Ͱ͖Δ • ͲͷΤϥʔ͕ɺͲ͔͜Β΍ͬͯ͘Δ͔Λ஌Δ͜ͱ͕Ͱ͖Δ ʢΤϥʔυϝΠϯ͕ܕ͔Β൑அͰ͖Δʣ

    • ύλʔϯϚονϯά͕໢ཏత • BAD: υϝΠϯຖʹΤϥʔܕͷม׵͕ඞཁ • େྔͷ mapError ม׵ͱɺωετͨ͠enumΤϥʔܕఆٛ
  8. BADͳਓͨͪᐌ͘ɺ ʮύλʔϯϚονϯάͰ ΤϥʔॲཧʢέʔεΛ໢ཏʣ Λ͢Δඞཁੑ͕΄ͱΜͲͳ͍ ͷͰɺΤϥʔܕ͸ඞཁͳ͍ʯ ʮ΋͠෼ذ͕ඞཁͰ͋Ε͹ɺ as?ΩϟετΛ࢖͑͹े෼ʯ

  9. Ͱ΋GOODͳਓͨͪ͸ ͜͏ݴ͏ Τϥʔܕ͸ɺ ΤϥʔॲཧΛ͢Δ ͨΊ͚ͩʹ࢖͏΋ ͷͰ͸ͳ͍

  10. NoError Uninhabited (empty) error type

  11. NoError ͱ͸ʁ • enum NoError: Swift.Error {} • ஋Λੜ੒͢Δ͜ͱ͕Ͱ͖ͳ͍ (ྫɿNever)

    • NoError ΋·ͨ Error • ୅਺తσʔλܕʹ͓͚Δʮ0ʯ • θϩܕʢϘτϜʣ͕͋Δͱɺܕͷදݱ͕ΑΓ๛͔ʹͳΔ
  12. // ࢖༻ྫɿReactiveSwift ͷ UI Binding // (`Error == NoError` ͷΈͰ࢖͑Δ)

    static func <~ <Source: BindingSource> ( provider: Self, source: Source ) -> Disposable? where Source.Value == Value, Source.Error == NoError { ... } // Bindingྫ (Note: Signal = Hot Observable) let alphaSignal: Signal<CGFloat, NoError> = ... view.reactive.alpha <~ alphaSignal
  13. NoError ͷ࢖༻ྫ • Signal<Value, NoError> • ΤϥʔΛྲྀ͞ͳ͍ Observable • RxSwift.Driver

    ౳ͷผͷܕΛ༻ҙ͢Δඞཁ͕ͳ͍ • Result<Value, NoError> • ੒ޭͷΈΛѻ͏ʢ Result<Value>Ͱ͸දݱͰ͖ͳ͍ʣ • ී௨ʹ Value Λ࢖͑͹ྑ͍Μ͡Όʁ → ྑ͘ͳ͍
  14. Result<Value, NoError> Value ͷཧ༝ ΋͠ɺObservable<T, E> -> Result<T, E> ʹม׵͢Δؔ਺

    ͕͋Δ৔߹ʢྫɿ ReactiveSwift.firstʣ // Note: SignalProducer = Cold Observable extension SignalProducer { public func first() -> Result<Value, Error>? { ... } }
  15. Result<Value, NoError> Value ͷཧ༝ ΋͠ɺΤϥʔܕύϥϝʔλͷͳ͍ Result<T>ͷੈքͩͱɾɾɾ extension SignalProducer { public

    func first() -> Result<Value>? { ... } } extension SignalProducer where Error == NoError { // ઈରʹΤϥʔ͠ͳ͍ͷͰɺ͜͜Ͱ͸`Result<Value>?` Λ࢖͍ͨ͘ͳ͍ public func first() -> Value? { ... } } ແବʹΦʔόʔϩʔυΛॻ͘ඞཁ͕ൃੜ !"
  16. ਺ֶʢݍ࿦ʣతʹݴ͏ͱɾɾɾ • Result<Value, NoError> Value • ྆ऀ͸ʮಉ͡ܕʯͰ͸ͳ͍͕ɺʮಉܕʢisomorphicʣʯ • ૬ޓม׵Ͱ͖Δʢٯࣹ͕ଘࡏʣ •

    ܕʹͩ͜ΘΔ → දݱྗ্͕͕Δ → ந৅ԽͰ͖Δ • Result<T> ΍ Observable<T> ͸දݱྗʹ๡͍͠ • NoError (θϩͷଘࡏ) ͸Ғେ
  17. Swift Poem: Why I prefer typed error https://gist.github.com/inamiy/ e3f5f7524f1bcdc582c2ff8dbbba58dd

  18. None
  19. Thanks! Yasuhiro Inami @inamiy