A colossal Dreamer: GR鐵塔-天生我材

[Swift] Int 의 양수구간만 사용할 때 임의 값 활용하는 비법. 본문

Development/랑구지(vbscript javascript java c# c++ objectiveC)

[Swift] Int 의 양수구간만 사용할 때 임의 값 활용하는 비법.

江多林 2022. 8. 5. 15:19

Like this:

public struct Demand {
    public static let unlimited: Self = .init(demand: UInt(Int.max) + 1)

    public static func max(_ value: Int) -> Self {
        .init(demand: UInt(value))
    }

    private var _demand: UInt

    private init(demand: UInt) {
        _demand = demand
    }
}

Demand 값은 양수만 갖는다.

Demand 는 양수외에 특이값 무제한 이라는 속성도 가질 수 있다.

 

이런 경우 외부 노출값은 Int 형식으로 사용하고,

내부값을 UInt 를 사용하여,

Int 형식의 범위에는 포함되지 않고, UInt 로만 표현 가능한 값을 활용해서

관리할 수 있게 된다.

 

위 unlimited 는 UInt(9223372036854775808) 값으로 표현한다.

= UInt(Int.max)  + 1
= 9223372036854775807 + 1
= 9223372036854775808

따라서, 그외에 추가로 필요한 값을 UInt(Int.max) + n 형식으로

충분히 정의해서 관리할 수 있다.