LoginSignup
1
0

More than 5 years have passed since last update.

reduceの途中経過を使う

Posted at

某質問サイトの質問で思いついたものなのですが、僕の中のreduceの有用性が大幅にアップしたので書いておきます。

UIKitってよくわからないのでちゃんと動くのかわかりません
雰囲気で!

文字列の配列からラベルを作成し並べて表示する


let view = UIView()

["Label01", "Label02", "Label03", "Label04"]
  .map { title -> UILabel in
    let label = UILabel()
    label.text = "\(title)"
    label.font = UIFont.systemFont(ofSize: 15)
    label.textColor = UIColor.white
    label.textAlignment = .center
    label.sizeToFit()

    return label
  }
  .reduce(CGFloat(0)) { left, label in

    label.frame.origin = CGPoint(x: left, y: 40)
    view.addSubview(label)

    return left + label.frame.size.width
}
1
0
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
0