LoginSignup
0
1

More than 3 years have passed since last update.

Swift言語 一定の範囲内でループする数値

Last updated at Posted at 2021-05-04

コピペ用

例えば 99 の次が 0 で, 逆に 0 の前が 99 のようにしたい時に使う。

増加: ... 97 < 98 < 99 < 0 < 1 < 2 ...
減少: ... 3 > 2 > 1 > 0 > 99 > 98 ...

extension_Int.swift
extension Int {

    /// looped value in range
    func looped(in range: ClosedRange<Self>) -> Self {
        let min = range.lowerBound
        let max = range.upperBound
        if self < min {
            return max - ((min - self - 1) % (max - min))
        }
        else if max < self {
            return min + ((self - max - 1) % (max - min))
        }
        else {
            return self
        }
    }
}

使い方

一度ループを無視した計算をした後に、 .looped(in:) を使う

99 + 1 = 100
0 - 1 = -1

let a = 100.looped(in: 0...99)
// a: 0

let b = (-1).looped(in: 0...99)
// b: 99

さいごに

99 + 300 のように、ループが何周も回っている場合にも対応しています。
自動でループする型を作りたい人は @propertyWrapper と組み合わせれば良さそうですね。

0
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
0
1