1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Kingfisherの`|>`演算子について

Posted at

はじめに

Kingfisherを使っていて|>という演算子を初めてみて、Swiftにこの演算子はないはず!と気になったので調べてみました。

気になった実際のコード

Kingfisherにあるサンプルコード

let url = URL(string: "https://example.com/high_resolution_image.png")
let processor = DownsamplingImageProcessor(size: imageView.bounds.size)
             |> RoundCornerImageProcessor(cornerRadius: 20)
imageView.kf.indicatorType = .activity
imageView.kf.setImage(
    with: url,
    placeholder: UIImage(named: "placeholderImage"),
    options: [
        .processor(processor),
        .scaleFactor(UIScreen.main.scale),
        .transition(.fade(1)),
        .cacheOriginalImage
    ])
{
    result in
    switch result {
    case .success(let value):
        print("Task done for: \(value.source.url?.absoluteString ?? "")")
    case .failure(let error):
        print("Job failed: \(error.localizedDescription)")
    }
}

この部分です

let processor = DownsamplingImageProcessor(size: imageView.bounds.size)
             |> RoundCornerImageProcessor(cornerRadius: 20)

結論 カスタム演算子だった

Kingfisherの中を|>で検索してカスタムしているコードを見つけました。

infix operator |>: AdditionPrecedence
public func |>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor {
    return left.append(another: right)
}

以下ChatGPT解説

infix operator |>: AdditionPrecedence

この行は、|> という新しい中置(infix)演算子を定義しています。AdditionPrecedenceは、この新しい演算子の優先順位を定義しており、+ や - のような加算・減算の演算子と同じ優先順位になります。

public func |>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor

この行は、新しく定義した |> 演算子の動作を定義しています。この関数は、ImageProcessor 型の left と right の二つの引数を受け取り、新しい ImageProcessor を返します。

return left.append(another: right)

この行では、left(左側のImageProcessor)の append メソッドを呼び出して、right(右側のImageProcessor)を追加(結合)します。その結果、連鎖的に画像処理を行う新しい ImageProcessor が返されます。

このカスタム演算子のおかげで、DownsamplingImageProcessor と RoundCornerImageProcessor のような異なる画像処理を簡単に組み合わせることができます。これにより、コードが読みやすくなり、連鎖的な画像処理の記述が簡潔になります。

おわりに

この記事が演算子についてわかりやすくまとめてくれています。ありがとうございます!

ちなみに|>を使わない書き方

let processor = DownsamplingImageProcessor(size: iconImageView.bounds.size)
            .append(another: RoundCornerImageProcessor(cornerRadius: 10))
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?