LoginSignup
4
3

More than 3 years have passed since last update.

CombineのflatMapを書いたらiOS14以上しか使われないって怒られる件について

Last updated at Posted at 2020-12-12

初投稿です。@dsxsxsxsです。
ここ最近本格的にCombineを使いはじめました。
割としょうもない話をしたいと思います。

怒られる実装

flatMapNoNo.swift
["hoge"].publisher
    .flatMap { _ in
        URLSession.shared.dataTaskPublisher(for: URL(string: "https://qiita.com")!)
    }

上記コードはなぜか上手く行かず、'flatMap(maxPublishers:_:)' is only available in iOS 14.0 or newerっとコンパイラーに怒られる。
そんなわけないですよね。

解決案

upstreamにsetFailureType(to:)を繋いであげれば大丈夫。

flatMapYaYa.swift
["hoge"].publisher
    .setFailureType(to: URLError.self)
    .flatMap { _ in
        URLSession.shared.dataTaskPublisher(for: URL(string: "https://qiita.com")!)
    }

どういうこと?

iOS14以降オンリーのメソッドを呼んでしまったからです。
定義がこうなっています:

flatMapFromNeverFail.swift
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
extension Publisher where Self.Failure == Never {
    public func flatMap<P>(maxPublishers: Subscribers.Demand = .unlimited, _ transform: @escaping (Self.Output) -> P) -> Publishers.FlatMap<P, Publishers.SetFailureType<Self, P.Failure>> where P : Publisher
}

Failure型がNeverの場合、setFailureType(to:)を内部でやってくれるflatMapが追加されましたという。
ちなみに、switchToLatest()も同様です。🍎さんはいつも通り、さり気なくサプライズを用意してくれます。

switchToLatestFromNeverFail.swift
@available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
extension Publisher where Self.Failure == Never, Self.Output : Publisher {
    public func switchToLatest() -> Publishers.SwitchToLatest<Self.Output, Publishers.SetFailureType<Self, Self.Output.Failure>>
}

どの人たちがよくハマるの?

  • XCode12から始めた人
  • Rxに慣れた人
  • サポートOSバージョンをiOS13指定しまっている人

僕は見事に上記3点フルコンボでした。😅

どの人たちがハマらないの?

  • 去年からCombineを始めたトップバッター勢
  • そもそもiOS13を切った勢

参考した記事

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3