LoginSignup
4
4

More than 5 years have passed since last update.

Swiftでプロパティの値の範囲を制限したいんだけど

Last updated at Posted at 2015-04-29

結論から先に。

struct TBNTempo {
  private static let MIN_BPM:Int = 40
  private static let MAX_BPM:Int = 360
  private static func check(b:Int) -> Int {
    return min(max(b, MIN_BPM), MAX_BPM)
  }
  var bpm:Int { // beats per minute
    didSet {
      bpm = TBNTempo.check(bpm)
    }
  }
  init(bpm b:Int) {
    bpm = TBNTempo.check(b)
  }
}

外部に使わせるプロパティとは別にプロパティを持たないとダメだった。
なんか負けた感じがする。

didSetでいけました。
@tottokotkd さんご指摘ありがとうございます。

以下、他に試したパターン

setter無限ループでNGだったパターン

struct TBNTempo {
  let MIN_BPM:Int = 40
  let MAX_BPM:Int = 360
  var bpm:Int { // beats per minute
    get { return bpm }
    set {
      switch newValue {
      case MIN_BPM...MAX_BPM:
        bpm = newValue // ここでsetter無限ループが起きるのでBAD_ACCESSで落ちる
      default:
        bpm = min(max(newValue, MIN_BPM), MAX_BPM) // ここでsetter無限ループが起きるのでBAD_ACCESSで落ちる
      }
    }
  }
  init(bpm b:Int) {
    bpm = b
  }
}
4
4
3

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
4